Spring annotation to verify - How can I verify that writing 2 characters per line is the actual state of the USA?

I am trying to use spring to check user input on the Internet to make sure that the two characters they enter are the actual state of the USA, is there any way to do this, hopefully using a predefined template? e.g. @State or something (if it was a legal annotation). Also, is there a good annotation commonly used for String street and in the String city field? This is not @NotNull and @NotEmpty

Any help would be greatly appreciated!

+4
source share
1 answer

, , @State, , , ConstraintValidator ( ), .

@Constraint(validatedBy = StateConstraintValidator.class)
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface State {

    String message() default "{State}";

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

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


public class StateConstraintValidator implements ConstraintValidator<String, String> {

    private static final Set<String> CODE_MAP = new HashSet<>(){
      {add("AR");}
      {add("AK");} //add more codes ...
    };

    @Override
    public void initialize(String state) { }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext cxt) {
        if(value == null) {
            return false;
        }
        return CODE_MAP.contains(value);
    }
}

.

+4

Source: https://habr.com/ru/post/1570364/


All Articles