dawdler-client-plug-validator
Module Introduction
A powerful front-end/back-end common validator. It supports common expression validation for both JS and the Java back end, is extensible, and can print back-end validation rules as front-end JS validation scripts (output through debug logs, for developers' reference; they are not delivered to the front end automatically). The Java back end supports grouping, inheritance and exclusion; the JS side supports validation extensions and various event extensions.
1. Adding the dependency in pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-client-plug-validator</artifactId>
2. Getting started
2.1 Viewing the validation rules supported by the system
Calling the static method help of RuleOperatorProvider lists the rules currently supported in the system (including custom extensions).
Below are some built-in validation rules that cover the vast majority of validation needs.
#stringRule list String-type validation rules
Status code:[ date ] Date validation
Status code:[ chineseWords ] Chinese character validation
Status code:[ realNumber ] Real number validation
Status code:[ IDCard ] ID card validation
Status code:[ lowercaseLetters ] Lowercase letters validation
Status code:[ negativeNumber ] Negative integer validation
Status code:[ positiveNumber ] Positive integer validation
Status code:[ webSite ] Website URL validation
Status code:[ number ] Integer validation
Status code:[ regularCharacter ] Chinese characters, letters or digits validation
Status code:[ natureNumber ] Natural number validation
Status code:[ capitalLetters ] Uppercase letters validation
Status code:[ phone ] Landline phone validation
Status code:[ notEmpty ] Not-empty validation
Status code:[ englishWords ] English letters validation
Status code:[ cellPhone ] Mobile phone number validation
Status code:[ email ] Email validation
#regexRule list Regex-type validation rules
Status code:[ ^contain:\[(.+)\]$ ] Contains-within-range validation, e.g. contain:[China,1] - the form must contain China or 1 !
Status code:[ ^minimum:([-+]?\d+(\.\d+)?$) ] Minimum value must not be less than the specified number, e.g. minimum:25 or minimum:25.32!
Status code:[ ^maxLength:([1-9]{1}\d*$) ] Length of a string or of the strings in an array must not exceed the specified length, e.g. maxLength:32!
Status code:[ ^maxItems:([1-9]{1}\d*$) ] Maximum number of selected items, maximum number of parameters, or length of a List or array must not exceed the specified number, e.g. maxItems:3!
Status code:[ ^minItems:([1-9]{1}\d*$) ] Maximum number of selected items, minimum number of parameters, or length of a List or array must not be less than the specified number, e.g. minItems:3!
Status code:[ ^noContain:\[(.+)\]$ ] Does-not-contain-within-range validation, e.g. noContain:[China,1] - the form must not contain China or 1 !
Status code:[ ^maximum:([-+]?\d+(\.\d+)?$) ] Maximum value must not be greater than the specified number, e.g. maximum:25 or maximum:25.32!
Status code:[ ^minLength:([1-9]{1}\d*$) ] Length of a string or of the strings in an array must not be less than the specified length, e.g. minLength:3!
2.2 Configuring the validator
Create a file ending in {controllerName}-validator.xml in the same directory as the controller.
The validator supports validating application/x-www-form-urlencoded, multipart/form-data, application/json (@RequestBody), http-header (@RequestHeader) and @PathVariable variables in antPath.
Example:
Define UserController.java and UserController-validator.xml.
Content of UserController-validator.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<validator><!-- Root node -->
<validator-fields><!-- Root node defining field information -->
<validator-field name="userid" explain="User Id">
<![CDATA[notEmpty&positiveNumber]]>
</validator-field><!-- Field information node; @name field name, @explain field description, @globalRules places keys from the global alias configuration file and, when filled in, is combined with the validation rules of this field (@globalRules is deprecated because it was rarely needed and hard to understand). <![CDATA[]]> holds the validation rules, whose content is the rules supported by the system (including custom extensions) -->
<validator-field name="username" explain="User name">
<![CDATA[notEmpty&maxLength:32]]>
</validator-field>
<validator-field name="password" explain="Password">
<![CDATA[notEmpty&maxLength:32]]>
</validator-field>
<validator-field name="age" explain="Age">
<![CDATA[positiveNumber]]>
</validator-field>
<validator-field name="platform" explain="Platform">
<![CDATA[notEmpty&positiveNumber]]>
</validator-field>
</validator-fields>
<validator-fields-groups><!-- Field groups -->
<!-- Field groups: if several APIs in the same Controller need to validate some of the same fields, create a group and reference its id via refgid from each of them.
Groups can reference each other via refgid as well; if this creates mutual dependencies the system reports an error! -->
<validator-fields-group id="add"><!-- Field group node; @id is the group identifier, referenced by other groups or mapping validators -->
<validator ref="userid"/><!-- Field within the group; @ref references a definition in validator-field.
If it does not exist there it is looked up in the global global-validator.xml; @refgid references another group; @ref and @refgid can be used together. -->
<validator refgid="edit"/>
</validator-fields-group>
<validator-fields-group id="edit">
<validator ref="username"/>
<validator ref="password"/>
<validator ref="age"/>
</validator-fields-group>
</validator-fields-groups>
<validator-mappings><!-- Validator mappings -->
<validator-mapping name="/user/regist"><!-- Validator; name is the request URI, i.e. the concrete API address defined by RequestMapping.
Note: if the class has a RequestMapping definition, the value on the class and the value on the method must be combined.
@skip skips certain validations; multiple rules can be skipped, separated by , (English comma), containing the @name of validator-field entries.
@method specifies the request method; valid values are GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, and when not specified the mapping applies to all methods. Different methods can be defined for the same name; at request time the mapping with a matching method is preferred, falling back to a mapping without a specified method. -->
<validator refgid="add" skip="age,username"/> <!-- The age and username validations are skipped -->
</validator-mapping>
<validator-mapping name="/user/edit" method="POST"><!-- @method="POST" means this mapping only applies to POST requests -->
<validator refgid="edit"/>
<validator ref="platform" type="header"/><!-- type is the field type; supported: param (the default when omitted; standard http request parameter), header (@RequestHeader), body (@RequestBody), path (@PathVariable). -->
</validator-mapping>
</validator-mappings>
<global-validator><!-- Global validator; every request method of this Controller is validated. Generally not used much -->
<validator ref="userid"/><!-- Description: fields for global validation. @ref references @name in validator-field, including that field; @refgid references other groups (equivalent to an include) -->
<validator ref="platform" type="header"/><!-- type is the field type; supported: param (the default when omitted; standard http request parameter), header (@RequestHeader), body (@RequestBody), path (@PathVariable). -->
</global-validator>
</validator>
3. Back-end validation configuration
3.1 validate-global-variable.properties global validation rule variables (deprecated because it was rarely needed and hard to understand)
The configuration file used to define global validation rule variables
nm32=notEmpty&maxLength:32
The above defines a global rule named nm32: notEmpty means it must not be empty and maxLength:32 means the maximum length must not exceed 32 characters.
You can freely combine any rules provided by the system or extended ones, joined with the & symbol.
Use the globalRules attribute to reference global validation rule variables
3.2 global-validator.xml reference (deprecated because it was rarely needed and hard to understand)
The configuration file used to define global validation rules; global validation rules can be referenced by validator-fields-group or by validator-mapping.
Example:
<global-validator>
<validator-fields>
<validator-field name="username" explain="User name" globalRules="nm32"></validator-field>
<validator-field name="email" explain="Email" rules="email" globalRules="nm32"></validator-field>
<validator-field name="phone" explain="Phone" rules="phone"></validator-field>
</validator-fields>
</global-validator>
The example above defines validation rules for the three fields username, email and phone.
The rule of the username field uses globalRules, where nm32 is the nm32 defined in validate-global-variable.properties.
The rule of the email field uses globalRules, where nm32 is the nm32 defined in validate-global-variable.properties.
4. Back-end custom rule extension
When the built-in rules do not meet your real development needs, you can extend them in either of the following two ways.
4.1 Extending string-type validation rules
Extend the StringRuleOperator class and implement the validate and toString methods.
Take club.dawdler.clientplug.web.validator.operators.NumberRuleOperator as an example. NumberRuleOperator is the system's implementation of the number rule, used to validate whether a string or the values in an array are integers.
Example:
public class NumberRuleOperator extends StringRuleOperator {
public static final String RULE_KEY = "number";//Rule key
public static final String REGEX = "(^-\\d+$)|(^\\d+$)";//Regular expression
public static final String EXPLAIN = "Integer validation";//Description
public NumberRuleOperator() {
super(RULE_KEY, REGEX, EXPLAIN);
}
@Override
public String validate(Object value) {
return validate(value, "Please enter an integer!");
}
@Override
public String toString() {
return EXPLAIN;
}
}
4.2 Extending regex-type validation rules
Extend the RegexRuleOperator class and implement the validate and toString methods.
Take club.dawdler.clientplug.web.validator.operators.MaxLengthRuleOperator as an example. MaxLengthRuleOperator is the system's rule implementation for validating that the number of characters does not exceed the specified range; usage: maxLength:32, at most 32 characters.
Example:
public class MaxLengthRuleOperator extends RegexRuleOperator {
public static final String RULE_KEY = "^maxLength:([1-9]{1}\\d*$)";//Regular expression
public MaxLengthRuleOperator() {
super(RULE_KEY);
}
//Implementation below
@Override
public String validate(Object value, Matcher matcher) {
boolean flag = true;
int i = Integer.parseInt(matcher.group(1));
String error = "Must not exceed " + i + " characters!";
if (value == null)
return null;
if (value instanceof String) {
if (isEmpty(value.toString()))
return null;
if (((String) value).trim().length() > i)
return error;
}
if (value instanceof String[]) {
String[] values = (String[]) value;
for (String v : values) {
if (isEmpty(v)) {
continue;
}
if (v.trim().length() > i) {
flag = false;
break;
}
}
} else if (value instanceof List) {
List values = (List) value;
for (Object o : values) {
if (isEmpty(o.toString())) {
continue;
}
if (o.toString().trim().length() > i) {
flag = false;
break;
}
}
}
if (!flag)
return error;
return null;
}
@Override
public String toString() {
return "Length of a string or of the strings in an array must not exceed the specified length, e.g. maxLength:32!";
}
}
5. Injecting validators
RuleOperatorProvider provides the registerRuleOperator and registerRuleOperatorScanPackage methods to add validators to the scan.
registerRuleOperator takes a RuleOperator entity object and adds only that object's implementation.
registerRuleOperatorScanPackage takes a Class object and adds all RuleOperator implementations in that Class's package.
5.1 Adding scanned validators in a listener
For listeners see WebContextListener
package com.anywide.yyg.user.web.listener;
import jakarta.servlet.ServletContext;
import club.dawdler.clientplug.web.listener.WebContextListener;
import club.dawdler.clientplug.web.validator.RuleOperatorProvider;
import club.dawdler.core.annotation.Order;
import com.anywide.yyg.user.validator.operators.RegPasswordRuleOperator;
@Order(1)
public class UserWebContextListener2 implements WebContextListener{
@Override
public void contextInitialized(ServletContext servletContext) {
RuleOperatorProvider.registerRuleOperatorScanPackage(RegPasswordRuleOperator.class);//Add scanned validators; scans and adds all rules in the same package
/* RegPasswordRuleOperator uo = new RegPasswordRuleOperator();
RuleOperatorProvider.registerRuleOperator(uo);*/ //Load only the specified validator
RuleOperatorProvider.help();//Generate documentation for developers
}
@Override
public void contextDestroyed(ServletContext servletContext) {
}
}
5.2 Adding scanned validators via the scanned component packages
Validators in packages configured for component scanning are injected; see Scanned component package configuration.
6. Front-end JS validation framework
dawdler-validator.js is a front-end framework compatible with the back-end validation expressions.
6.1 Usage
Include dawdler-validator.js; it internally provides an instance sir_validator (sir is a tribute to linuxsir, which used this variable name back in the day).
You can declare another object
<script language="javascript">
var validator = new Validator();
</script>
The usual reason to declare another object is that several forms on the same page need validation.
<script language="javascript" src="dawdler-validator.js"></script>
6.2 Adding validation rules
Call the addRule method to add validation rules; addRule accepts an object as well as an array of objects.
addRule supports the following five properties on the passed object:
id: The field id or name. For checkboxes or radio buttons it is the name attribute; for ordinary fields it is the id.
viewName: The description of the field, e.g. User name.
validateRule: The validation rule; several can be combined with &.
alertFunction: A notification method or the id of a notification component. See the alertFunction example
buildFunction: Binds the events that trigger validation. See the buildFunction example
6.2.1 Examples of adding validation rules
Example 1:
//Add a validation rule for a single field
sir_validator.addRule({
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty"
});
Example 2:
//Add validation rules for several fields, using an array
sir_validator.addRule([{
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty&maxLength:16"
},{
"id": "password",
"viewName": "Password",
"validateRule": "notEmpty&maxLength:16"
}]);
6.2.2 alertFunction example
Example of passing a notification method:
//Define a method
function password_alert_function(obj, error) {
//obj is the field object and error is the error message.
alert("password_alert_function:" + obj + ":" + error);
}
sir_validator.addRule({
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty",
"alertFunction": password_alert_function //Just pass the method directly; the password_alert_function defined above is called
});
Example of passing the id of a notification component:
<!--Define an html element-->
<span id="password_alert_span"></span>
sir_validator.addRule({
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty",
"alertFunction": "password_alert_span" //Pass the id of the element defined above directly; the validation result is set on that element via innerHTML.
});
6.2.3 buildFunction example
Binds the click event and the onblur event.
sir_validator.addRule({
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty",
"buildFunction": "click,onblur"
});
6.3 Appending validation rules
Call the appendRule method to append validation rules. The first parameter of appendRule is the field id and the second is the rule expression; appending adds to the existing rules.
Example:
//Add a validation rule to the username field requiring a minimum length of 3 characters.
sir_validator.appendRule("username","minLength:3");
6.4 Removing a specific rule from a field
Call the removeRule method to remove a specific validation rule from a field. The first parameter of removeRule is the field id and the second is the rule expression; if the field contains the rule passed as the second parameter it is removed.
Example:
//Remove the rule requiring a minimum length of 3 characters from the username field.
sir_validator.removeRule("username","minLength:3");
6.5 Removing all validation rules from a field
Call the removeAllRule method to remove all validation rules from a field; the parameter of removeAllRule is the field id.
Example:
//Remove all validation rules from the username field.
sir_validator.removeAllRule("username");