1

I want to test whether the data in the form field is a number using Java Bean Validation.

The following example tests the size but it can still accept letters:

@Basic(optional = false)
@NotNull
@Size(min = 1, max = 5, message = "must be 5 digits or less")
@Column(name = "code")
private String code;
M. Justin
  • 14,487
  • 7
  • 91
  • 130
GreyWolf18
  • 141
  • 1
  • 3
  • 13
  • Does this answer your question? [How to validate number string as digit with hibernate?](https://stackoverflow.com/questions/19537664/how-to-validate-number-string-as-digit-with-hibernate) – M. Justin Jan 12 '22 at 20:00

1 Answers1

1

Yes, actually there are several:

@Digits(integer=6, fraction=2): The value of the field or property must be a number within a specified range. The integer element specifies the maximum integral digits for the number, and the fraction element specifies the maximum fractional digits for the number.

@DecimalMax("30.00") or @DecimalMin("5.00"): The value of the field must be greater or equal/lower or equal to the value specified in the annotation.

@Min("10") or @Max("10"): Same as @Decimal, but the value of the field must be an integer.

Also, if none of these are good for your needs, you can use @Pattern with a regex.

Source: https://docs.oracle.com/javaee/7/tutorial/bean-validation001.htm

Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40
  • i thought the Digits DecimalMax DecimalMin Min() Max() annotations could only be used for numeric type variables? – GreyWolf18 Mar 08 '20 at 16:02
  • They can be used to validate `String` type variables as well. – Ervin Szilagyi Mar 08 '20 at 16:17
  • @GreyWolf18 — According to the Javadocs, [`@DecimalMax`](https://jakarta.ee/specifications/platform/9/apidocs/jakarta/validation/constraints/decimalmax) supports `String` (and other `CharSequence`) values, but [`@Max`](https://jakarta.ee/specifications/platform/9/apidocs/jakarta/validation/constraints/max) does not. Likewise for the "min" variations of these two annotations. Hibernate Validator does extend `@Min` & `@Max` to `CharSequence` types: [guide](https://docs.jboss.org/hibernate/validator/6.1/reference/en-US/html_single/#validator-defineconstraints-spec), however. – M. Justin Jan 08 '22 at 15:07