@TOC

Today, I wrote a registration function in the company, and added regular verification to the registration. The implementation method was PROMISE. Originally, the rough way was to directly write, but I have ocD and optimized it accordingly.

The environment

vue uniapp

demand

  1. Use regular validation for phone numbers;
  2. Authenticating the password using a regular;
  3. Chaining calls with a Promise;
  4. The verification result should be prompted to the user

Began to make

1. Write regular expressions first

1.1 Baidu’s entire re

// Password authentication/ ^ (? =.*\d)(? =.*[a-z])(? =.*[A-Z]).{8.12} $/// Verify the phone number/ ^1[34578] [09 -] {9} $/Copy the code

1.2 Verification Function

/ / cell phone
function reg_password(value){
	const rule = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 8, 12 {} $/
	return rule.test(value)
}
// The password is 8 to 12 characters long and contains uppercase and lowercase letters and digits. Special characters can be used
function reg_mobile(value){
	const rule = / ^ 1 [34578] [0-9] {9} $/
	return rule.test(value)
}
// Whether to complete the form completely
function isComplete(){
	if(this.mobile &&this.nickName &&this.password &&this.passwordConfirm &&this.userName){
		if(this.password ! = =this.passwordConfirm){
			return([""."The two entered passwords are inconsistent, please re-enter them.".false])}else{
			return([""."".true])}}else{
		return(["2"."Please complete the information.".false])}}Copy the code

1.3 Calling the validation function

if(this.isComplete()){
	if(this.reg_mobile()){
		if(this.reg_password()){ ... }}else{... }}else{... }Copy the code

But this is nice to write down, but it’s not a little low, yes, so let’s optimize the code.

1.4 Optimizing code Structure with Policy Pattern (a Design pattern)

The policy pattern is a simple design pattern that allows us to define rules and then execute them directly by taking one of them when we use them, so that we don’t have to use a lot of big if else’s

// Policy mode
var rule = {
	add:() = >"add".del:() = >"del".ref:() = >"ref",}Copy the code

2. Start optimization

2.1 Using policy Patterns to define rules

const options ={
	// Basic verify that the passwords are complete and consistent
	isComplete: () = >{
		if(this.mobile &&this.nickName &&this.password &&this.passwordConfirm &&this.userName){
			if(this.password ! = =this.passwordConfirm){
				return([""."The two entered passwords are inconsistent, please re-enter them.".false])}else{
				return([""."".true])}}else{
			return(["2"."Please complete the information.".false])}},// Password authentication
	passwordREG : (key,message,value) = >{
		const resultREG = [key, message, (/ ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 8, 12 {} $/).test(value)]
		return resultREG[2];
	},
	// Verify the phone number
	mobileREGL: (key, message, value) = >{
		const resultREG = [key, message, (/ ^ 1 [34578] [0-9] {9} $/).test(value)];
		return resultREG[2]; }}Copy the code

According to the pass parameter call rules to achieve validation

The corresponding function is called by passing in different arguments

options['isComplete'] (); options['passwordREG'] (this.password);
options['mobileREGL'] (this.mobile);
Copy the code

If both are true then the interface is called. If both are false then the user is prompted to reenter

So that’s all the code, Can git push the 😎 🐱 πŸ’» 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁

Wait, can we really push? 🐱 πŸš€

Is there no room for improvement? 🐱 🏍

There must be. Please see ———–πŸ±πŸ‰=====++++++ πŸ‰

Optimize the way

1. Use Promise chained calls

Using promises makes it easy to call our functions one by one and handle errors easily.

isComplete: () = >{
    return new Promise((resolve,reject) = >{
        if(this.mobile &&this.nickName &&this.password &&this.passwordConfirm &&this.userName){
            if(this.password ! = =this.passwordConfirm){
                reject([""."The two entered passwords are inconsistent, please re-enter them.".false])}else{
                resolve([""."".true])}}else{
            reject(["2"."Please complete the information.".false])}})},// Password authentication
passwordREG : (key,message,value) = >{
     return new Promise((resolve, reject) = >{
         const resultREG = [key,
         					message,
         					(/ ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 8, 12 {} $/).test(value)]
         resultREG[2]? resolve(resultREG) : reject(resultREG);
         // if(resultREG[2]){
         // resolve(resultREG)
         // }else{
         // reject(resultREG)
         // }})},// Verify the phone number
mobileREGL: (key, message, value) = >{
   return new Promise((resolve, reject) = >{
        const resultREG = [key, message, (/ ^ 1 [34578] [0-9] {9} $/).test(value)]
        resultREG[2]? resolve(resultREG) : reject(resultREG);
        // if(resultREG[2]){
        // resolve(resultREG)
        // }else{
        // reject(resultREG)
        // }})}Copy the code

I believe that careful students have found that (/^(? =.\d)(? =.[a-z])(? =.*[a-z]).{8,12}$/).test(string).

const rule = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 8, 12 {} $/;
returnrule.test(string); = = >return (/ ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 8, 12 {} $/).test(string) 
Copy the code

Go straight from two lines to one line

The first return is a new Promise() and the arguments are resolve and reject. The first is a successful function and the second is a failed return function to pass to the next Promise

1.2 Upgrade the code of the invoke rule

Since we call three promises at a time, we use promise.all () to pass in an array and execute in order

 // promise.all Execute the array
const arrREG = [
     options['isComplete'](),
     options['passwordREG'] ("Password"."The format is not correct. Please enter a 8-12 digit password with upper and lower case letters and digits. Special characters can be used.".this.password
						    ),
     options['mobileREGL'] ("Cell phone number"."Format is not correct, please enter the correct mobile phone number".this.mobile)
 ]
Copy the code

First, use the extension operator in ES6… [] Expand the current array and insert the three promises

// Verify user input data one at a time

var ret = false;
var _this = this;
return Promise.all([...arrREG]).then((result) = >{
	// Define an identifier to get the result returned by the Promise, and return this number to the upper function
    result.forEach(item= >{
        _this.ret = item[2]})return _this.ret
}).catch((err) = >{
    _this.ret = err[2]
    // Return an error message to the user
    _this.Message("i am erring")
    return _this
})
Copy the code

How’s that? If you don’t want to add a rule to the list, you can add a rule to the list. If you want to add a rule to the list, you can add a rule to the list. If you want to add a rule to the list, you can add a rule to the list.