The @Digits
annotation is used to validate that a numeric field has a valid integer or fractional digits. It is a built-in constraint in the Java Bean Validation (JSR-380) specification and can be used with any Java bean property that is of a numeric type (such as int
, long
, float
, etc.).
The @Digits
annotation has two attributes: integer
and fraction
, which specify the maximum number of integer and fractional digits, respectively. For example, if you specify integer=6
and fraction=2
, the annotated field will be valid if it contains a number with at most 6 integer digits and 2 fractional digits.
The @Digits
annotation also has a message
attribute, which allows you to specify a custom error message to be displayed if the constraint is violated.
How to use @Digits validation in spring boot
The @Digits
annotation is used to validate that a numeric field has a valid integer or fractional digits. It has the following attributes:
integer
: Specifies the maximum number of integer digits.fraction
: Specifies the maximum number of fractional digits.message
: Specifies the error message to display if the constraint is violated.groups
: Specifies the validation groups that this constraint belongs to.payload
: Specifies additional meta-data to be carried along with the constraint.
Here is an example of how you can use the @Digits
annotation:
import javax.validation.constraints.Digits;
public class MyBean {
@Digits(integer = 6, fraction = 0, message = "Invalid pincode")
private String pincode;
// getters and setters
}
This will ensure that the pincode
field is a valid integer with no more than 6 digits. If the input does not match the constraint, a ConstraintViolationException
will be thrown when you try to validate the MyBean
object. The error message specified in the message
attribute will be included in the exception.
You can then use the MyBean
class in your Spring application, and the pincode
field will be validated to ensure that it only contains digits and has no more than 6 digits. For example, you might use this bean in a Spring MVC controller:
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@GetMapping("/")
public ModelAndView showForm() {
return new ModelAndView("form", "bean", new MyBean());
}
@PostMapping("/")
public ModelAndView submitForm(MyBean bean, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("form");
}
return new ModelAndView("success");
}
}
If the input does not match the @Digits
constraint, a ConstraintViolationException
will be thrown when you try to bind the request parameters to the MyBean
object. You can catch this exception and handle the error appropriately in your application.