Custom validation

This commit is contained in:
uPagge 2021-03-22 19:50:41 +03:00
parent 6ee6872892
commit 9799bd7e5c
No known key found for this signature in database
GPG Key ID: 964B40928E4C9088
3 changed files with 42 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package org.sadtech.example.springvalidation.dto;
import lombok.Getter;
import lombok.Setter;
import org.sadtech.example.springvalidation.valid.CapitalLetter;
import javax.persistence.Column;
import javax.persistence.Entity;
@ -26,6 +27,7 @@ public class PersonDto {
private Long id;
@NotBlank
@CapitalLetter
private String name;
@Min(1)

View File

@ -0,0 +1,24 @@
package org.sadtech.example.springvalidation.valid;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = CapitalLetterValidator.class)
@Documented
public @interface CapitalLetter {
String message() default "должно быть с большой буквы";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,16 @@
package org.sadtech.example.springvalidation.valid;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CapitalLetterValidator implements ConstraintValidator<CapitalLetter, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value != null && !value.isEmpty()) {
return Character.isUpperCase(value.charAt(0));
}
return true;
}
}