Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Min validation on String

In the javadoc of @Min (javax.validation.constraints.Min) it states that only numerical values can be validated.

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER}) @Retention(value=RUNTIME) @Documented @Constraint(validatedBy={}) public @interface Min

The annotated element must be a number whose value must be higher or equal to the specified minimum.

Supported types are:

BigDecimal
BigInteger
byte, short, int, long, and their respective wrappers

Note that double and float are not supported due to rounding errors (some providers might provide some approximative support)

null elements are considered valid

When I add the annotation to a String it takes the value of the String and converts it to a BigDecimal and then checks the value. As if the String contains a BigDecimal value.

Questions:

  1. Where is this documented?
  2. Why does Eclipse Mars not accept this?

See Eclipse (compiler) message:

The javax.validation.constraints.Min constraint supports the following types: java.math.BigDecimal, java.math.BigInteger, byte, short, int, long, and their respective wrapper types.

Test.java

import javax.validation.constraints.Min;

public class Test {
  @Min(10)
  String quantity;
}

The code works as expected.

like image 772
Milo van der Zee Avatar asked Mar 08 '26 22:03

Milo van der Zee


1 Answers

You are probably using Hibernate Validator as implementation of the Bean Validation API. Quoting its documentation:

BigDecimal, BigInteger, byte, short, int, long and the respective wrappers of the primitive types; Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number

As you correctly said in your question, the Bean Validation specification of @Min annotation does not mandate implementors to support String (or CharSequence). This is a Hibernate feature only and may not work with another implementation.

Note that in the appendix C of the spec, the following is said:

Persistence Provider should optionally recognize and try to apply the following constraints as well:

  • @Min / @Max on numeric columns (TODO String too?)
like image 190
Tunaki Avatar answered Mar 11 '26 12:03

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!