📜  使用 jQuery 进行表单验证

📅  最后修改于: 2021-11-25 03:14:47             🧑  作者: Mango

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

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

方法:

  1. 首先,您需要创建一个index.html文件,该文件由 Bootstrap 4表单组成,其中用户名电子邮件密码确认密码作为输入字段。在“body”标签的底部,包含“app.js”文件,其中包含用于表单验证的jQuery 代码。
  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验证代码。

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

输出:下面是用户直接点击提交按钮时生成的输出。

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

HTML 是网页的基础,用于通过构建网站和 Web 应用程序进行网页开发。您可以按照此 HTML 教程和 HTML 示例从头开始学习 HTML。

CSS 是网页的基础,用于通过样式化网站和 Web 应用程序进行网页开发。您可以按照此 CSS 教程和 CSS 示例从头开始学习 CSS。

jQuery 是一个开源 JavaScript 库,它简化了 HTML/CSS 文档之间的交互,它以其“少写,多做”的理念而广为人知。
您可以按照此 jQuery 教程和 jQuery 示例从头开始学习 jQuery。