majdi
majdi

Reputation: 43

Hibernate validation: give the ability to user to only enter a digits(number) not instead

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.

Upvotes: 0

Views: 690

Answers (3)

wnameless
wnameless

Reputation: 531

I assume that the JSF form data is already mapped into a POJO, here is the example you can achieve the behavior you want by using SpELScriptAssert. BTW, I am the author of this library.

@SpELScriptAssert(
      script = "input instanceof T(Integer)",
      message = "'#{input}' must be a number between #{T(Integer).MIN_VALUE} and #{T(Integer).MAX_VALUE} Example: 9346")
public class Form {
  public Object input = "10S";
}

Upvotes: 0

SirCipher
SirCipher

Reputation: 1054

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;

Upvotes: 0

Lucas Oliveira
Lucas Oliveira

Reputation: 3477

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();

Upvotes: 0

Related Questions