0

While studying BeanValidation from documented here, I came to know that @Digits supports String datatype. here the snap-shot from documentation.

package javax.validation.constraints;

/**
 * The annotated element must be a number within accepted range
 * Supported types are:
 * <ul>
 * <li><code>BigDecimal</code></li>
 * <li><code>BigInteger</code></li>
 * <li><code>String</code></li>
 * <li><code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>,
 * and their respective wrapper types</li>
 * </ul>
 * <p/>
 * <code>null</code> elements are considered valid
 *
 * @author Emmanuel Bernard
 */

How can Digits behave for String type? On what base @Digit will validate to String type? Will it behave like digit regex validation (@Pattern)?

Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82

1 Answers1

1

JSR-303 defines an interface so you should check what the implementation does. If you use Hibernate Validator, String's validator that supports @Digit constraint is defined in the DigitsValidatorForCharSequence class (note that the String class implements the CharSequence interface).

That implementations parses a given String and if it is a valid BigDecimal the validator returns true.

Here is the isValid method defined in the aforementioned class (and the private method that is used to parse the value):

public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {
    //null values are valid
    if ( charSequence == null ) {
        return true;
    }

    BigDecimal bigNum = getBigDecimalValue( charSequence );
    if ( bigNum == null ) {
        return false;
    }

    int integerPartLength = bigNum.precision() - bigNum.scale();
    int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();

    return ( maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength );
}

private BigDecimal getBigDecimalValue(CharSequence charSequence) {
    BigDecimal bd;
    try {
        bd = new BigDecimal( charSequence.toString() );
    }
    catch ( NumberFormatException nfe ) {
        return null;
    }
    return bd;
}

Link to the source code: https://github.com/hibernate/hibernate-validator/blob/e20c12aa0aba6e2bf21a2da7cefd74d06c2e2710/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators/bv/DigitsValidatorForCharSequence.java

Bartosz Mikulski
  • 525
  • 3
  • 17