简体   繁体   中英

How to validate only when content is filled in Spring MVC?

I have a class with several attributes. One is month and another is year. It is not mandatory to fill those fields. Leaving both blank should be accepted. But in case just one of them is filled, both of them should be validated (according to @Min and @Max below) so that it is a valid month/year date. How do I implement that condition? The code below makes it mandatory to fill both. Doesn't accept the first condition (both empty).

@Entity
public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

    //Other attributes here
    
    @Min(value=1, message="Invalid month")
    @Max(value=12, message="Invalid month")
    private int month;
    
    @Min(value=1900, message="Invalid year")
    @Max(value=2100, message="Invalid year")
    private int year;

JSR-303 addresses this. You can create a custom validator annotation @ValidMonthAndYear on Person.java .

ValidMonthAndYear.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(
    validatedBy = {MonthAndYearValidator.class}
)
public @interface ValidMonthAndYear {
    String message() default "Missing Month or Year";

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

    Class<? extends Payload>[] payload() default {};
}

MonthAndYearValidator.java

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MonthAndYearValidator implements ConstraintValidator<ValidMonthAndYear, Person> {


    public boolean isValid(Person person, ConstraintValidatorContext context) {
        boolean isValid = false;
        //Logic here to validate Person attributes
        return isValid;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM