Skip to main content

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");

6.6 Setting the validation rules of a field​

Call the setRule method to set the validation rules of a field. The first parameter of setRule is the field id and the second is the rule expression; existing rules on the field are overwritten.

Example:

//Set the validation rule of the username field to not empty.
sir_validator.setRule("username","notEmpty");

6.7 Adding expressions that do not skip empty validation​

Call addNoSkip to add expressions that are not skipped when the value is empty. The system has three built in: notEmpty, maxItems and minItems. All three are executed when the field value is empty, because by default the validation framework does not execute validation expressions when the field value is empty.

Example:

//Make the email expression not skip empty validation; equivalent to email&notEmpty
addNoSkip("email");

6.8 Validating​

Call the validateAll method to validate. It returns a boolean: true means validation passed; false triggers the notification event (if an alertFunction, a global event or a global display element is configured, the corresponding configuration is used; otherwise alert is called by default).

Example:

//Normally used when submitting a form via ajax

if(!sir_validator.validateAll())return;//Validation failed, just return;

//Validation passed, call the back end via ajax

6.9 Binding the form submit event​

Call the buildFormValidate method to bind the form submit event; the parameter of buildFormValidate is the form id.

Example:

<!--Define a form with id myform-->
<form id="myform" action="create.do" method="POST">
<input type="text" name="username" value="" /><br/>
<input type="text" name="password" /> <br/>
<input type="submit" id="submit_onw" value="Submit" /><br/>
</form>
// Add validation rules
sir_validator.addRule([{
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty&maxLength:16"
},{
"id": "password",
"viewName": "Password",
"validateRule": "notEmpty&maxLength:16"
}]);
// Bind validation to the form with id= myform
sir_validator.buildFormValidate("myform");

6.10 Loading validation rules configured via html attributes (rarely used)​

Call the buildFormValidateAutoRule method to load validation rules configured via DOM attributes. The first parameter is the form id and the second is a boolean indicating whether to bind the form submit event.

In the example below the validation framework attributes are defined directly on the html fields; the attributes are exactly the same as those passed via an object. This approach is generally not recommended unless a dynamic form (as implemented in the dawdler-client-plug-velocity module) generates the attributes automatically.

Example:

<!--Define a form with id myform and define validation attributes-->
<form id="myform" action="create.do" method="POST">
<input type="text" name="username" viewName="User name" validateRule="notEmpty&maxLength:16" value="" /><br/>
<input type="text" name="password" viewName="Password" validateRule="notEmpty&maxLength:16"/> <br/>
<input type="submit" id="submit_onw" value="Submit" /><br/>
</form>
// Load the validation configuration from the DOM attributes; the second parameter true binds the onsubmit event.
sir_validator.buildFormValidateAutoRule("myform", true);

6.11 Global notification method​

Define a method or a global variable named globalAlertFunction to implement the global notification. A method takes precedence over a variable (if a rule defines alertFunction, alertFunction is called first).

If a method is defined it is called with the field object as the first parameter and the error message as the second.

Example of defining a method:

//This is also a way to restyle the notification element
function global_validate_error_function(obj, error) {
alert("validate_error:" + obj + ":" + error);
}

If a variable is defined, the error message or pass message is assigned to an element via innerHTML, where the element id is the validated field id plus global_validate_error_function. In the example below, errors are written via innerHTML into the user_error and password_error elements.

Example of defining a variable:

<form id="myform" action="create.do" method="POST">
<input type="text" name="username" viewName="User name"/><span id="username_error"></span><br/>
<input type="text" name="password" viewName="Password"/><span id="password_error"></span> <br/>
<input type="submit" id="submit_onw" value="Submit" /><br/>
</form>

var global_validate_error_function = "_error";
sir_validator.addRule([{
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty&maxLength:16"
},{
"id": "password",
"viewName": "Password",
"validateRule": "notEmpty&maxLength:16"
}]);
// Bind validation to the form with id= myform
sir_validator.buildFormValidate("myform");

6.12 Extending the front-end validation framework​

The front end supports two kinds of extensions, so that it can support extended expressions from the back end.

6.12.1 Extending front-end string-type validation rules​

Define a method whose name is the expression and whose parameter is the field value; returning true means validation passed, returning a string triggers the notification.

The following extends an expression called hello that only accepts hello and reports an error otherwise; the expression can be used alone or joined with &.

function hello(text){
if(text=='hello')return true;
return "You must enter hello !";
}

sir_validator.addRule({
"id": "username",
"viewName": "User name",
"validateRule": "notEmpty&hello"//Must not be empty and must be hello
});

6.12.2 Extending front-end regex-type validation rules​

Regex-type validation rules differ from string-type ones; for such needs refer to the maxLength/minItems family of implementations.

How to implement:

Call the addRegExp method to add a regex-type validation rule; a rule consists of (expression name:regex). Define a method whose name is the expression name; parameter 1 is the field value and parameter 2 is the array of regex matches.

Example:

The following is an implementation of a range validation expression


//Add the expression
sir_validator.addRegExp(/range:([0-9]+)-([0-9]+)/);

//Define a validation method named after the part before the colon; args[0] (args[1] in 1-based JS terms) is the first matched group, the next element the second group, and so on for N groups.
function range(value,args){
if(value<args[1])return "Must be greater than "+args[1];
if(value>args[2])return "Must be less than "+args[2];
}

sir_validator.addRule({
"id": "age",
"viewName": "Age",
"validateRule": "notEmpty&range:18-108"//Must not be empty and must be between 18 and 108
});