@Max anotation in spring boot

0
10
form dropdown in spring boot

In Spring Boot, the @Max annotation is used to specify that a field must be a number that is less than or equal to a specified maximum value. This annotation can be used on fields of any numeric type, including integral types (such as int and long) and floating-point types (such as float and double).

Here’s an example of how to use the @Max annotation:

public class User {
    ...
    @Max(100)
    private int age;
    ...
}

In this example, the age field is constrained to be a number that is less than or equal to 100. If a value greater than 100 is assigned to this field, a validation error will be triggered.

To use the @Max annotation, you will need to include the following import statement in your code:

import javax.validation.constraints.Max;

You will also need to enable validation in your Spring Boot application by adding the following dependency to your project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Then, in your controller, you can use the @Valid annotation to trigger validation of the model and the BindingResult to check for validation errors. If any errors are found, you can take appropriate action, such as returning an error message to the user.

@PostMapping("/register")
public String register(@Valid User user, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "register";
    }
    // proceed with registration
    ...
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here