Native JS makes form verification, which is the basic form verification method

Time:2022-5-18

Form verification is one of the most common functions of Web front-end, and it is also the basic skill of front-end development. Completing the development of a form verification by yourself also helps to deepen the understanding of string processing and regular expressions.

Basic form verification includes: letter verification, number verification, letter and number verification, Chinese character verification, password verification, date verification, mobile phone verification, email verification, password verification, etc.

Now let’s finish writing these verification codes. First, let’s see how the letters are verified. First write the required HTML code, create a form element with ID of formcontainer, add a text box and button to verify the English letters, and a span element behind the text box to store the prompt text. As follows:

English letter:

 

When developing, analyze the function step by step and then realize it, which can maintain a clear idea.

1. Get form elements and text box elements as follows:

var eFormContainer = document.getElementById('formContainer');
var eVerifyEn = document.getElementById('verifyEn');

 

2. Bind the submit event to the form element, which is used for verification when clicking the submit button.

eFormContainer.addEventListener('submit',function(event){
  
});

This example requires that when the verification is passed, a prompt will pop up indicating that the verification is passed; If the verification fails, the cursor will be positioned to the text box and a prompt of verification failure will be displayed behind the text box. Next, let’s see how to do it in the submit event function.

 

3. First declare relevant variables in the function and obtain the value of the text box. Bpass variable is used to judge whether it can pass the verification; Sprompt variable is prompt text; The svalue variable is the value of the text box. As follows:

eFormContainer.addEventListener('submit',function(event){
  var bPass = false;
  var sPrompt = '';
  var sValue = eVerifyEn.value;
});

 

4. Empty text box is not allowed. Judge whether svalue is an empty string. If yes, a prompt will be displayed behind the text box, and if the text box is activated, it is also necessary to prevent subsequent operations and default behavior. The code is as follows:

eFormContainer.addEventListener('submit',function(){
    /* ... */
    
    if(sValue.trim()==''){
        //Modify prompt text
        Sprompt = 'English letters cannot be empty!';
        //Position the cursor in the letter text box
        eVerifyEn.focus();
        //Display prompt text after text box
        //Gets the parent element of the text box
        let eParent = eVerifyEn.parentElement;
        //Get the span element where the prompt is stored
        let eSpan = eParent.getElementsByTagName('span')[0];
        //Add prompt in span element
        eSpan.innerHTML = sPrompt;
        //Block form submission
        event.preventDefault();
        //Block subsequent code execution
        return;
  }
  
});

 

5. Judge whether the input value meets the rules, that is, there are only English letters and no other characters. A regular expression is declared here to determine whether it is all English letters. As follows:

eFormContainer.addEventListener('submit',function(){
    /* ... */
    
    //Declare regular and judge whether all strings are English letters
    let reg = /^[a-zA-Z]+$/;
    bPass = reg.test(sValue);
  
});

 

6. Execute pass or block submission according to the regular judgment result.

eFormContainer.addEventListener('submit',function(){
    /* ... */
    
    if(bPass){
        //Pop up prompt for verification
        Alert ('pass verification ');
    }else{
        //Modify prompt text
        Sprompt = 'only English letters can be entered!';
        //Position the cursor in the letter text box
        eVerifyEn.focus();
        //Display prompt text after text box
        //Gets the parent element of the text box
        let eParent = eVerifyEn.parentElement;
        //Get the span element where the prompt is stored
        let eSpan = eParent.getElementsByTagName('span')[0];
        //Add prompt in span element
        eSpan.innerHTML = sPrompt;
        //Block form submission
        event.preventDefault();
    }
  
});

 

7. When entering content in the text box, the following prompt should be deleted, as shown below:

//Bind the input event on the eformcontainer element and delegate the input events of all text boxes to the eformcontainer element,
  //The advantage of this is that you don't need to add events to every text box.
  eFormContainer.addEventListener('input',function(event){
    //Get current text box
    let eInput = event.target;
    //Gets the parent element of the text box
    let eParent = eInput.parentElement;
    //Get the span element where the prompt is stored
    let eSpan = eParent.getElementsByTagName('span')[0];
    //Clear prompt
    eSpan.innerHTML = '';
  });

The complete JavaScript code at this time is as follows:

function fnFormVerify(){
    //Get form elements
    var eFormContainer = document.getElementById('formContainer');
    //Get validation letter text box
    var eVerifyEn = document.getElementById('verifyEn');
    //Bind submit events to form elements
    eFormContainer.addEventListener('submit',function(){
      //Declare the bpass variable, which is used to judge whether it passes the verification
      var bPass = false;
      //Declare the sprompt variable for prompt text
      var sPrompt = '';
      //Obtain the value of the letter text box, ensure that it is not equal to empty, and then judge whether the value contains non English letters. The code is as follows:
      var sValue = eVerifyEn.value;
      //Ensure that it is not equal to empty
      if(sValue.trim()==''){
        //Modify prompt text
        Sprompt = 'English letters cannot be empty!';
        //Position the cursor in the letter text box
        eVerifyEn.focus();
        //Display prompt text after text box
        //Gets the parent element of the text box
        let eParent = eVerifyEn.parentElement;
        //Get the span element where the prompt is stored
        let eSpan = eParent.getElementsByTagName('span')[0];
        //Add prompt in span element
        eSpan.innerHTML = sPrompt;
        //Block form submission
        event.preventDefault();
        //Block subsequent code execution
        return;
      }

      //Declare regular and judge whether all strings are English letters
      let reg = /^[a-zA-Z]+$/;
      bPass = reg.test(sValue);
      if(bPass){
        //Pop up prompt for verification
        Alert ('pass verification ');
      }else{
        //Modify prompt text
        Sprompt = 'only English letters can be entered!';
        //Position the cursor in the letter text box
        eVerifyEn.focus();
        //Display prompt text after text box
        //Gets the parent element of the text box
        let eParent = eVerifyEn.parentElement;
        //Get the span element where the prompt is stored
        let eSpan = eParent.getElementsByTagName('span')[0];
        //Add prompt in span element
        eSpan.innerHTML = sPrompt;
        //Block form submission
        event.preventDefault();
      }
    });

    //Bind the input event on the eformcontainer element and delegate the input events of all text boxes to the eformcontainer element,
    //The advantage of this is that you don't need to add events to every text box.
    eFormContainer.addEventListener('input',function(event){
      //Get current text box
      let eInput = event.target;
      //Gets the parent element of the text box
      let eParent = eInput.parentElement;
      //Get the span element where the prompt is stored
      let eSpan = eParent.getElementsByTagName('span')[0];
      //Clear prompt
      eSpan.innerHTML = '';
    });
  }
  fnFormVerify();

The effect is as shown in the figure:

 

 

Then we need to complete digital verification, letter and number verification, Chinese character verification, password verification, date verification, mobile phone verification, email verification, password verification, etc. If each verification is written in this way, it will be very cumbersome and there will be a lot of code. Therefore, you need to encapsulate a string verification function to return the verification result. When submitting, call each text box in turn.

Add HTML elements as follows:

English letter:
    
    English and figures:
    
    Number:
    
    chinese characters:
    
    Date:
    
    Email:
    
    mobile phone:
    
    password:
    
    确认password:

 

Modify JS code again:

1. Get form elements and all text boxes as follows:

//Get form elements
  var eFormContainer = document.getElementById('formContainer');
  //Get validation letter text box
  var eVerifyEn = document.getElementById('verifyEn');
  //Get English and numeric text boxes
  var eVerifyEnNum = document.getElementById('verifyEnNum');
  //Get numeric text box
  var eVerifyNum = document.getElementById('verifyNum');
  //Get Chinese character text box
  var eVerifyCn = document.getElementById('verifyCn');
  //Get date text box
  var eVerifyDate = document.getElementById('verifyDate');
  //Get mailbox text box
  var eVerifyEmail = document.getElementById('verifyEmail');
  //Get mobile text box
  var eVerifyPhone = document.getElementById('verifyPhone');
  //Get password text box
  var eVerifyPwd = document.getElementById('verifyPwd');
  //Get confirmation password text box
  var eVerifyForPwd = document.getElementById('verifyForPwd');

 

2. Encapsulate a validation function and pass in three parameters: elem is a text box element, reg is a regular expression, and text is a prompt keyword. As follows:

function fnVerify(elem,reg,text){
  //Gets the character entered in the text box
  var sValue = elem.value;
  //Gets the parent element of the text box
  let eParent = elem.parentElement;
  //Get the span element where the prompt is stored
  let eSpan = eParent.getElementsByTagName('span')[0];

  //Determine whether the text box character is empty
  if(sValue.trim()==''){
    //Position the cursor in the text box
    elem.focus();
    //Display prompt text after text box
    eSpan. InnerHTML = text + 'cannot be empty!';
    //Return false
    return false;
  }

  //Judge whether the string conforms to the rules
  if(reg.test(sValue)){
    //If yes, return true
    return true;
  }else{
    //Position the cursor in the text box
    elem.focus();
    //Display prompt text after text box
    eSpan. InnerHTML = text + 'incorrect format!';
    //If not, false is returned
    return false;
  }
}

 

3. Bind the submission event on the form element, as shown below:

eFormContainer.addEventListener('submit',function(event){
  //Declare the bpass variable, which is used to judge whether it passes the verification
  var bPass = false;
  
  //Verify text box formatting one by one
  Bpass = fnverify (everifyen, / ^ [a-za-z] + $/, 'English letter')&&
          Fnverify (everifyennum, / ^ [a-za-z0-9] * $/, 'English and numbers')&&
          Fnverify (everifynum, / ^ \ d * $/, 'number')&&
          Fnverify (everifycn, / ^ [\ u0391 - \ uffe5] + $/, 'Chinese character')&&
          Fnverify (everifydate, / ^ (\ D {2}| \ D {4}) - \ D {1,2} - \ D {1,2} $/, 'date')&&
          fnVerify(eVerifyEmail,/^([a-zA-Z0-9]+[_|\_|\.]?)* [a-zA-Z0-9][email protected]([a-zA-Z0-9]+[_|\_|\.]?)* [a-zA-Z0-9]+\. [a-za-z] {2,3} $/, 'mailbox')&&
          Fnverify (everifyphone, / ^ (((13 [0-9] {1}) | (15 [0-9] {1}) | (18 [0-9] {1})) + \ D {8}) $/, 'phone')&&
          Fnverify (everifypwd, / ^ [\ w! @# $% ^ & *? \ (\)] {6,16} $/, 'password');

  //The confirmation password shall be consistent with the password, and a separate verification shall be added
  if(eVerifyPwd.value !== eVerifyForPwd.value){
    //Get confirm password parent element
    let eParent = eVerifyForPwd.parentElement;
    //Get prompt span element
    let eSpan = eParent.getElementsByTagName('span')[0];
    //Prompt error
    eSpan. InnerHTML = 'confirm that the password should be consistent with the password';
    //Activation confirmation password input box
    eVerifyForPwd.focus();
    //Block subsequent actions
    bPass = false;
  }

  if(bPass){
    //Pop up prompt for verification
    Alert ('pass verification ');
    event. preventDefault(); // The actual work cannot have this line. This is to prevent the default behavior of the form.
  }else{
    //Block form submission
    event.preventDefault();
  }
  
});

There should be an error prompt in the text box. Otherwise, there should be an error prompt in the back, which needs to be solved.

 

4. Bind the input event on the eformcontainer element to delete the prompt text during input.

eFormContainer.addEventListener('input',function(event){
  //Get current text box
  let eInput = event.target;
  //Gets the parent element of the text box
  let eParent = eInput.parentElement;
  //Get the span element where the prompt is stored
  let eSpan = eParent.getElementsByTagName('span')[0];
  //Clear prompt
  eSpan.innerHTML = '';
});

Here, a complete form verification page is basically completed; This example tutorial uses the submit form submission event, but now in the actual development, it is rare to submit the form directly. It is hereby explained to avoid misleading readers.

 

Recommended Today

JMeter – the difference between HTTP request following redirection and automatic redirection

Automatic redirection: After httpclient receives the request, if the request contains a redirection request, httpclient can jump automatically, but only for get and head requests. If this item is checked, the “follow redirection” will be invalid; Automatic redirection can automatically turn to the final target page, but JMeter does not record the content of the […]