Created
January 8, 2021 05:25
-
-
Save silentsudo/a7e86d76bb4f21812febc8d1ac044002 to your computer and use it in GitHub Desktop.
custom-hibernate-class-type-validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo.validation; | |
import lombok.Getter; | |
import lombok.NoArgsConstructor; | |
import lombok.Setter; | |
import org.springframework.validation.annotation.Validated; | |
import org.springframework.web.bind.annotation.PostMapping; | |
import org.springframework.web.bind.annotation.RequestBody; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
import javax.validation.*; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import java.util.regex.Pattern; | |
@Validated | |
@RestController | |
@RequestMapping(path = "/demo") | |
public class OptionValidController { | |
@PostMapping(path = "/person") | |
public Person doSomething(@Valid @RequestBody Person person) { | |
return person; | |
} | |
@PostMapping(path = "/station") | |
public Station doSomething(@RequestBody Station station) { | |
return station; | |
} | |
@Constraint(validatedBy = {PersonClassOptionalEmailValidator.class}) | |
@Target({ElementType.TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface PersonalEmailValid { | |
String message() default "Invalid Email address"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
} | |
public static class PersonClassOptionalEmailValidator implements ConstraintValidator<PersonalEmailValid, Person> { | |
public static final String EMAIL_REGEX = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"; | |
private final Pattern pattern; | |
public PersonClassOptionalEmailValidator() { | |
pattern = Pattern.compile(EMAIL_REGEX); | |
} | |
@Override | |
public boolean isValid(Person person, ConstraintValidatorContext constraintValidatorContext) { | |
if (person.contactInformation != null) { | |
return pattern.matcher(person.contactInformation.email).matches(); | |
} | |
return false; | |
} | |
} | |
@Getter | |
@Setter | |
@NoArgsConstructor | |
static class ContactInformation { | |
String phone; | |
String email; | |
} | |
@Getter | |
@Setter | |
@NoArgsConstructor | |
@PersonalEmailValid | |
static class Person { | |
@Valid | |
ContactInformation contactInformation; | |
} | |
@Getter | |
@Setter | |
@NoArgsConstructor | |
static class Station { | |
@Valid | |
ContactInformation contactInformation; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment