📜  使用jQuery进行表单验证

📅  最后修改于: 2021-05-25 18:09:55             🧑  作者: Mango

表单验证是确认用户在输入字段中输入的相关信息的过程。在这里,我们将使用jQuery验证一个简单的表单,该表单包含用户名,密码和确认密码。

先决条件:您必须了解HTML,CSS,JavaScript和jQuery的基础知识。

方法:

  1. 首先,您需要创建一个由Bootstrap 4表单组成的index.html文件,并使用usernameemailpassword确认password作为输入字段。在“ body”标签的底部,包括带有表单验证的jQuery代码的“ app.js”文件。
  2. 创建一个app.js文件,以验证代码中下面给出的整个表单。
  3. app.js文件中,准备好文档后,隐藏所有错误消息。对所有输入字段(例如用户名,电子邮件,密码和确认密码)执行验证任务。

index.html:以下HTML代码演示了用于用户输入的表单设计。

HTML



    
    
    
    
    
    
    
    

  

    

        Welcome to GeeksforGeeks     

       

      FORM VALIDATION USING JQUERY     

       
      
        
          
                                            
                    **Username is missing               
          
                
                                                                 Your email must be a valid email                          
             
                                            
                **Please Fill the password               
          
             
                                            
                  **Password didn't match               
          
                         
      
    
                 


Javascript
// Document is ready
$(document).ready(function () { 
     
// Validate Username
    $('#usercheck').hide();    
    let usernameError = true;
    $('#usernames').keyup(function () {
        validateUsername();
    });
      
    function validateUsername() {
      let usernameValue = $('#usernames').val();
      if (usernameValue.length == '') {
      $('#usercheck').show();
          usernameError = false;
          return false;
      } 
      else if((usernameValue.length < 3)|| 
              (usernameValue.length > 10)) {
          $('#usercheck').show();
          $('#usercheck').html
("**length of username must be between 3 and 10");
          usernameError = false;
          return false;
      } 
      else {
          $('#usercheck').hide();
      }
    }
  
   // Validate Email
    const email = 
        document.getElementById('email');
    email.addEventListener('blur', ()=>{
       let regex =
/^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
       let s = email.value;
       if(regex.test(s)){
          email.classList.remove(
                'is-invalid');
          emailError = true;
        }
        else{
            email.classList.add(
                  'is-invalid');
            emailError = false;
        }
    })
      
   // Validate Password
    $('#passcheck').hide();
    let passwordError = true;
    $('#password').keyup(function () {
        validatePassword();
    });
    function validatePassword() {
        let passwrdValue = 
            $('#password').val();
        if (passwrdValue.length == '') {
            $('#passcheck').show();
            passwordError = false;
            return false;
        } 
        if ((passwrdValue.length < 3)|| 
            (passwrdValue.length > 10)) {
            $('#passcheck').show();
            $('#passcheck').html
("**length of your password must be between 3 and 10");
            $('#passcheck').css("color", "red");
            passwordError = false;
            return false;
        } else {
            $('#passcheck').hide();
        }
    }
          
// Validate Confirm Password
    $('#conpasscheck').hide();
    let confirmPasswordError = true;
    $('#conpassword').keyup(function () {
        validateConfirmPasswrd();
    });
    function validateConfirmPasswrd() {
        let confirmPasswordValue = 
            $('#conpassword').val();
        let passwrdValue = 
            $('#password').val();
        if (passwrdValue != confirmPasswordValue) {
            $('#conpasscheck').show();
            $('#conpasscheck').html(
                "**Password didn't Match");
            $('#conpasscheck').css(
                "color", "red");
            confirmPasswordError = false;
            return false;
        } else {
            $('#conpasscheck').hide();
        }
    }
      
// Submitt button
    $('#submitbtn').click(function () {
        validateUsername();
        validatePassword();
        validateConfirmPasswrd();
        validateEmail();
        if ((usernameError == true) && 
            (passwordError == true) && 
            (confirmPasswordError == true) && 
            (emailError == true)) {
            return true;
        } else {
            return false;
        }
    });
});


app.js:以上HTML文件中使用了以下用于验证的jQuery代码。

Java脚本

// Document is ready
$(document).ready(function () { 
     
// Validate Username
    $('#usercheck').hide();    
    let usernameError = true;
    $('#usernames').keyup(function () {
        validateUsername();
    });
      
    function validateUsername() {
      let usernameValue = $('#usernames').val();
      if (usernameValue.length == '') {
      $('#usercheck').show();
          usernameError = false;
          return false;
      } 
      else if((usernameValue.length < 3)|| 
              (usernameValue.length > 10)) {
          $('#usercheck').show();
          $('#usercheck').html
("**length of username must be between 3 and 10");
          usernameError = false;
          return false;
      } 
      else {
          $('#usercheck').hide();
      }
    }
  
   // Validate Email
    const email = 
        document.getElementById('email');
    email.addEventListener('blur', ()=>{
       let regex =
/^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
       let s = email.value;
       if(regex.test(s)){
          email.classList.remove(
                'is-invalid');
          emailError = true;
        }
        else{
            email.classList.add(
                  'is-invalid');
            emailError = false;
        }
    })
      
   // Validate Password
    $('#passcheck').hide();
    let passwordError = true;
    $('#password').keyup(function () {
        validatePassword();
    });
    function validatePassword() {
        let passwrdValue = 
            $('#password').val();
        if (passwrdValue.length == '') {
            $('#passcheck').show();
            passwordError = false;
            return false;
        } 
        if ((passwrdValue.length < 3)|| 
            (passwrdValue.length > 10)) {
            $('#passcheck').show();
            $('#passcheck').html
("**length of your password must be between 3 and 10");
            $('#passcheck').css("color", "red");
            passwordError = false;
            return false;
        } else {
            $('#passcheck').hide();
        }
    }
          
// Validate Confirm Password
    $('#conpasscheck').hide();
    let confirmPasswordError = true;
    $('#conpassword').keyup(function () {
        validateConfirmPasswrd();
    });
    function validateConfirmPasswrd() {
        let confirmPasswordValue = 
            $('#conpassword').val();
        let passwrdValue = 
            $('#password').val();
        if (passwrdValue != confirmPasswordValue) {
            $('#conpasscheck').show();
            $('#conpasscheck').html(
                "**Password didn't Match");
            $('#conpasscheck').css(
                "color", "red");
            confirmPasswordError = false;
            return false;
        } else {
            $('#conpasscheck').hide();
        }
    }
      
// Submitt button
    $('#submitbtn').click(function () {
        validateUsername();
        validatePassword();
        validateConfirmPasswrd();
        validateEmail();
        if ((usernameError == true) && 
            (passwordError == true) && 
            (confirmPasswordError == true) && 
            (emailError == true)) {
            return true;
        } else {
            return false;
        }
    });
});

输出:以下是用户直接单击“提交”按钮时生成的输出。

以下是用户在表单中输入无效详细信息时生成的输出。