preface
The project needs to use form validation, in this article step by step elegant form validation to get ideas, according to the needs of a form validation class encapsulation
Train of thought
Requirements:
- You can customize authentication rules
- Regular expressions that can be customized for validation
- Multiple rules or regular expressions can be validated simultaneously
- reusable
According to the above requirements, but also for their own learning practice ES6 writing Class, in the article code for a certain rewrite. The method of defining validation rules in a Class is more intuitive and clear than the ES5 method of changing stereotypes.
Concrete implementation:
-
Create an object whose key is the name of the value that you want to validate and whose value is the value that you want to validate.
let data = {username: this.username}; Copy the code
-
Create an array of validation rule objects for the data to be validated. Each object in this array has a validation rule for each value to be validated.
let rules = [{key: "username".regExp: ["email"."phone"].required: true}]; Copy the code
-
Call the method of the validation class, take these two objects as arguments, traverse the rule array, execute the validation function on the values to be validated in turn, and finally return the validation information of all values to be validated.
code
Encapsulated validation class
/** * Validation class *@param {Object} Data Indicates the data to be verified. The format is {username:" ABC "} *@param {Array} Rules Specifies the verification rule. The format is [{key:"username", require:true,regExp: ["email", "phone"]}] *@return {Object} Verify information **/
class Validator {
// The required constructor for the class
constructor(){}// Verify the method
validate(data, rules) {
let validatedInfos = {}; // Store authentication information
// Iterate over each rule object corresponding to each data in the number group
rules.forEach((rule) = > {
let value = data[rule.key]; // Get the validation data for this rule
// Determine if necessary
if (rule.required) {
let info = this.required(value);// Verify information
if (info.required) {
this.setDefaultObj(validatedInfos, rule.key);
validatedInfos[rule.key] = info;
} else {
this.setDefaultObj(validatedInfos, rule.key);
validatedInfos[rule.key] = info;
return; // If the required value is null, the return is not executed}}// Filter key and require keys
let restKeys = Object.keys(rule).filter(
(key) = >key ! = ="key"&& key ! = ="required"
);
// Walk through the rest of the rules
restKeys.forEach((restKey) = > {
if (this[restKey]) {
let info = this[restKey](value, rule[restKey]);// Verify information
this.setDefaultObj(validatedInfos, rule.key);
validatedInfos[rule.key][restKey] = info;
} else {
throw `${restKey}The rule does not exist; }}); });// Returns validation information
return validatedInfos;
}
// Each validation rule
/ / required
required(value) {
if(! value && value ! = =0) {
return { "required": false };
} else {
return { "required": true}; }}// Minimum length
minLength(value, l) {
if (value.length <= l) {
return { "minLength": true}}else {
return { "minLength": false}}}// Regular expressions
regExp(value, regExpArray) {
// regExp can be user-defined or built-in
let regExpInfos = [];
regExpArray.forEach((regExpName) = > {
switch (regExpName) {
case "phone":
if (!/^1\d{10}$/.test(value)) {
regExpInfos.push("Mobile phone format error");
}
break;
case "email":
if (!/^([a-zA-Z0-9]+[-_.]?) +@[a-zA-Z0-9]+.[a-z]+$/.test(value)) {
regExpInfos.push("Email format error");
}
break;
default:
// Custom regex
if(! regExp.test(value)) { regExpInfos.push("Formatting error");
}
break; }});return regExpInfos;
}
// Generate objects for easy assignment
setDefaultObj(obj, key){ obj[key] = obj[key] || {}; }}export { Validator };
Copy the code
use
let data = {
username: this.username,
password: this.password,
};
// Validate the rule
let rules = [
{
key: "username".regExp: ["email"."phone"].required: true}, {key: "password".required: true,},];let validator = new Validator();
let validatedInfo = validator.validate(data, rules);
console.log("Verify information", validatedInfo);
Copy the code
The return value
Scene:
Enter a value for username that does not match the email format and does not match the phone format
The value of password is empty