0

I have a jsf form and I have an input which normally accept only number(integer) . I want to custom the error message when the user enter a string or char in this field. I want the validation in the data layer thats mean with hibernate annotation. I don't want use this default message if the user enter a string instead of integer, I want using my custom error message.

: '10S' must be a number between -2147483648 and 2147483647 Example: 9346

Please the attached image can explain well. How could I achieve this please.

image to explain more

Thank you in advance.

majdi
  • 43
  • 1
  • 9
  • see [hibernate doc](https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-message-interpolation.html) – akhambir Nov 27 '17 at 13:34

2 Answers2

0

You should implement your own javax.validation.MessageInterpolator

(from https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-validator-factory-message-interpolator)

Message interpolators are used by the validation engine to create user readable error messages from constraint message descriptors.

In case the default message interpolation algorithm described in Chapter 4, Interpolating constraint error messages is not sufficient for your needs, you can pass in your own implementation of the MessageInterpolator interface via Configuration#messageInterpolator()

as shown in the example below:

package org.hibernate.validator.referenceguide.chapter09;

public class MyMessageInterpolator implements MessageInterpolator {

    @Override
    public String interpolate(String messageTemplate, Context context) {
        //...
        return null;
    }

    @Override
    public String interpolate(String messageTemplate, Context context, Locale locale) {
        //...
        return null;
    }
}

You can configure your validator to use your custom interpolator like that:

ValidatorFactory validatorFactory = Validation.byDefaultProvider()
        .configure()
        .messageInterpolator( new MyMessageInterpolator() )
        .buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
Lucas Oliveira
  • 3,357
  • 1
  • 16
  • 20
  • it looks redundant in this case. Why not use out of the box solution like: `@NotNull(message = "The manufacturer name must not be null")` – akhambir Nov 27 '17 at 13:40
  • looks like difficult to implement such custom message – majdi Nov 27 '17 at 13:58
0

You can achieve this with the @Range annotation

@Range(min = -2147483648, max = 2147483647, message= ": '10S' must be a number between -2147483648 and 2147483647 Example: 9346")
long value;
SirCipher
  • 933
  • 1
  • 7
  • 16
  • Woops, sorry. I misunderstood the question. I understand what you mean now and I will update my question later on. – SirCipher Dec 06 '17 at 09:39