Java template validation annotations and using a regex template behave differently
I have a regex
^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\\[\\]|; :\\s]*$)(?!.*[/])
and I tried regex using two approaches for the string "hello":
java.util.regex.Pattern: pass the testjavax.validation.constraints.Pattern(annotation): it will throw an error that contains invalid values.
Does anyone know why these two behave differently?
At least for your test string, "hello"it seems that two regular expressions behave the same, so it's hard for you to find out what you are working in without additional information.
This short program checks both. The sample is displayed below.
public class RegexTest {
static final String REGEX = "^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\\[\\]|; :\\s]*$)(?!.*[/])";
static final String TEST = "hello";
public static class TestObject {
@javax.validation.constraints.Pattern(regexp=REGEX)
String name;
}
public static void main(String[] args) {
test1();
test2();
}
public static void test1() {
java.util.regex.Pattern p = java.util.regex.Pattern.compile(REGEX);
Matcher m = p.matcher(TEST);
System.out.println(m.matches()); // false, ie, doesn't match
}
public static void test2() {
TestObject to = new TestObject();
to.name = TEST;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<TestObject>> violations = validator.validate(to);
for(ConstraintViolation<TestObject> violation : violations) {
System.out.println(violation.getMessage()); // One violation, "must match"
}
}
}
false
INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.2.4.Final
must match "^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\[\]|; :\s]*$)(?!.*[/])"