“This is the third day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.
Before we have implemented database deployment through Docker -> article link here, not Docker want to know about specific can see my article: Docker guide to use
Next is the development of user module, here I directly use Mybatis – Plus to automatically generate projects, so some simple CRUD directly use Mybatis – Plus, because it is just a model to demonstrate learning on the line. Registration is a simple way to fill in the information and write a table. Here I use the @valid annotation to verify the information
@postMapping ("/reg") @operation (summary = "user registration ") public Map Insert (@requestBody @valid SysUser entity, BindingResult bindingResult) { if (bindingResult.hasErrors()) throw new RuntimeException(bindingResult.getFieldError().getDefaultMessage()); . / / throw calibration error return sysUserService insertUser (entity); }Copy the code
I’m going to put an @valid annotation in front of the entity class that I’m passing in, and BindingResult works with that annotation, and I’m going to return some validation error information back to the front end, so I’m going to throw it as an exception because I’ve configured a global exception handler and I’m going to return it in a uniform format, Refer to this article – >SpringBoot how to unify the backend return format. We will then add the annotations we need to the entity class to complete the validation
/** * passWord */ @notnull (message = "passWord cannot be empty ") private String passWord;Copy the code
For example, if I add @notnull (message = “passWord cannot be null “) to the passWord field, it means that the field is passed by the front end and cannot be null when it is verified. Message can be used to return a custom error message to the front end. In addition to @notnull, there are many other features that can be used to search for annotations. There are many articles on this topic, but I would like to talk about custom annotation verification.
We can copy the @notnull source code to write our own validation logic
The first step is to write annotations. I’m using the mobile phone number format validation as an example. After removing the unnecessary ones, I add a required() parameter to determine if this parameter is required.
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = {IsMobileValidator.class}) public @interface IsMobile { boolean required() default true; // Whether the parameter to be verified is mandatory String message() default "Mobile number format is wrong "; // Default error message Class<? >[] groups() default {}; Class<? extends Payload>[] payload() default {}; }Copy the code
Then we need to implement our own validation class IsMobileValidator in @Constraint(validatedBy = {isMobilevalidator.class}). ConstraintValidator this validation class is implemented by ConstraintValidator, which overwrites an initialization method and a validation method that reads require() and validates the phone number if it is required. If it is a non-mandatory parameter, check whether the parameter is empty first. If it is empty, check whether it is correct. If it is not empty, check the mobile phone number format and return.
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = false; @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.required(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (required) { return validatorUtil.isMobile(value); Else {if (stringutils.isempty (value)) {return true; } else { return validatorUtil.isMobile(value); }}}}Copy the code
There are many tools to verify the mobile phone number. I used this one:
private static final String REGEX_MOBILE ="((\+86|0086)? \s*)((134[0-8]\d{7})|(((13([0-3]|[5-9]))|(14[5-9])|15([0-3]|[5-9])|(16(2|[5-7]))|17([0-3]|[5-8])|18[0-9]|19(1|[8-9]))\d{ 8})|(14(0|1|4)0\d{7})|(1740([0-5]|[6-9]|[10-12])\d{7}))"; @return Boolean true: Yes false: no */ public static Boolean isMobile(String tel) {if (StringUtils.isEmpty(tel)){ return false; } return Pattern.matches(REGEX_MOBILE, tel); }Copy the code
You can write other custom verification according to your own needs, I also wrote a judgment ID card, see GitHub. The validation part is in the Validator package
Test it once you’re done, first add custom annotations to our entity class
Then add the @valid annotation to the controller layer’s pass-through entity
BindingResult. GetFieldError (.) getDefaultMessage calibration failure () returns the error message, with the postman test
After entering the correct mobile phone number, you can register successfully