0

I am using Java's Validator class to validate some input fields from my Spring Object class. I am validating URIs, and they can be in either format, http:/myURL/uri, or "readFromURI.v1". Originally, I was just validating the first part, so my Object class had:

@Pattern(regexp="[\\w\\s.,;:*&@(){}+-=?/|!\\[\\]%#$~]{0,512}", message="incorrect format")
private String URI;

Now, if the user selects a checkbox in my app, they will enter in the value as the second format, so I created a new regexp:

@Pattern.List({
  @Pattern(regexp="[\\w\\s.,;:*&@(){}+-=?/|!\\[\\]%#$~]{0,512}", message="incorrect format"),
  @Pattern(regexp="^\"(Create|Read|Update|Delete)[a-zA-Z]+.*vd+\"${0,512}", message="incorrect format")
})
private String URI;

The regexp is probably wrong for the second part, and I will probably ask that question at a later time. But now whenever I validate either format it fails both conditions. So I'm assuming that the way I wrote it, it's trying to apply both regex's. How can I choose one based on a value? That value field is in the same Class if that helps:

private String URI;
private boolean useHttp; //if true, validate using [\\w\\s.,;:*&@(){}+-=?/|!\\[\\]%#$~]{0,512}

1 Answer 1

1

You should write a custom validator, as explained here:

  1. Create a new annotation CustomConstraint annotated with @Constraint(validatedBy = CustomConstraintValidator.class)
  2. Have some class CustomConstraintValidator implements ConstraintValidator<CustomConstraint, YourType>
  3. Annotate YourType with @CustomConstraint
  4. Do your validation in your CustomConstraintValidator depending on your bean value.

Your validation will be able to check whatever field you want to test (I don't remember if class level constraint pass after each field level annotation pass, so you might have to check if URI is not null).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.