I have the following...


@Column
@ContactInfo
private String contactInfo;
...
private static final String EMAIL_PATTERN = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
    
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(value, "US"); // Specify default country code
            if (phoneUtil.isValidNumber(phoneNumber)) {
                return true; // Valid phone number
            }
        } catch (Exception e) {
            // Not a valid phone number, try email next
        }

        // Next, try to validate as an email
        return Pattern.matches(EMAIL_PATTERN, value);
}

@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public void addContact(@Valid PotentialContact contact) {
        contact.setId(Uuids.timeBased());
        potentialContactRepo.save(contact);
}

But when I run and pass sadsadsadsadsadas as contact info like this...

POST http://localhost:8080/contact
200
36 ms
POST /contact HTTP/1.1
User-Agent: PostmanRuntime/7.31.0
Accept: */*
Cache-Control: no-cache
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 109
Cookie: JSESSIONID=5CF0280370CFA0403A4645392E34A907
 
name=sadsadsadsadsadas&contactInfo=sadsadsadsadsadas&location=sadsadsadsadsadas&description=sadsadsadsadsadas
 
HTTP/1.1 200 OK

I would expect to get a 400 but instead I get a 200. What am I missing? Is there a more native way to handle this in Spring?

0

There are 0 best solutions below