Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring MVC validation, Is it possible to show only one error message per field at a time?

Example,

I have

@NotEmpty //tells you 'may not be empty' if the field is empty
@Length(min = 2, max = 35) //tells you 'length must be between 2 and 35' if the field is less than 2 or greater than 35
private String firstName;

Then I input an empty value.

It says, 'may not be empty length must be between 2 and 35'

Is it possible to tell spring to validate one at a time per field?

like image 518
Kevin Avatar asked Sep 26 '11 12:09

Kevin


People also ask

How do you validate a user's input within a number range in Spring MVC?

In Spring MVC Validation, we can validate the user's input within a number range. The following annotations are used to achieve number validation: @Min annotation - It is required to pass an integer value with @Min annotation. The user input must be equal to or greater than this value.

What is the purpose of custom validations in Spring MVC?

It is necessary to validate user input in any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side.


1 Answers

Yes it is possible. Just create your own annotation like this:

@Documented
@Constraint(validatedBy = {})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@NotEmpty
@Length(min = 2, max = 35)
public @interface MyAnnotation {

    public abstract String message() default "{mypropertykey}";

    public abstract Class<?>[] groups() default {};

    public abstract Class<?>[] payload() default {};
}

important part is the @ReportAsSingleViolation annotation

like image 132
František Hartman Avatar answered Sep 18 '22 09:09

František Hartman