jquery form validation verifies that the form is not empty through class

  • 2020-09-16 07:21:10
  • OfStack

During the development of the system, some form data is always required. If jQuery is used to verify through ID, it will not only affect the efficiency, but also omission, which is not easy to maintain later.

This chapter describes how to use jQuery to configure class for integration 1 validation for forms. (ID1 pages can only be used once; class can be quoted multiple times)

1: Add class to input. The name can be set at will, but each input needs to be kept at 1. In the case of this chapter, calss is set to noNull. (If input already has class attribute, it can be directly added to the end)

2: Add an attribute for input to obtain the field later through jquery as a prompt. The case prompt property for this chapter is notNull.

3: Through jQuery, traverse all forms in the page with calss as noNull to verify whether it is empty. If it is, get the field of notNull to prompt for empty.

For details, please refer to the following case. This chapter for input radio select, checkbox type etc are expounded.


<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
</head>
<body>
  <form>
      <!-- input -->
      <div>
         The name : <input type="text" name="name" notNull=" The name " class="form-control noNull"> 
      </div>
      <br>
      <!-- radio -->
      <div>
        gender :
        male <input type="radio" name="sex" value="0" class="noNull" notNull=" gender ">
        female <input type="radio" name="sex" value="1" >
      </div>
      <br>
      <!-- select -->
      <div>
         Age: 
        <select name="age" class="noNull" notNull=" age ">
          <option value =""> Please select a </option>
          <option value ="1">1</option>
          <option value ="2">2</option>
        </select>
      </div>
      <br>
      <!-- checkbox -->
      <div>
         Interest: 
         Play a ball game <input type="checkbox" name="hobby" value="1" class="noNull" notNull=" Interest in ">
         Sing a song <input type="checkbox" name="hobby" value="2">
         dancing <input type="checkbox" name="hobby" value="3">
      </div>
      <br>
     <button type="button" class="btn-c" onclick="bubmi()"> save </button>
  </form>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function bubmi(){
  $(".noNull").each(function(){
    var name = $(this).attr("name");
    if($(this).val()==""){
    alert($(this).attr('notNull')+" Can't be empty ");return false;
    }
    if($(this).attr("type")=="radio"){ 
      if ($("input[name='"+name+"']:checked").size() < 1){ 
        alert($(this).attr('notNull')+" Can't be empty !"); 
        return false; 
      } 
    }
    if($(this).attr("type")=="checkbox"){ 
      if ($('input[name="'+name+'"]:checked').size() < 1){ 
        alert($(this).attr('notNull')+" Can't be empty !"); 
        return false; 
      } 
    }    
  })  
}
</script>
</body>
</html>

Here is the jquery.validate.js validation plug-in

jquery. validate. js is one of the authentication plug-ins under jquery. With the advantages of jquery, we can quickly verify some common inputs and expand our own authentication methods.

For example, here is a form:


<form id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" class="required"/>
</p>
<p>
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" />
</p>
<p>
<label for="username">Username</label>
<input id="username" name="username" />
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password" />
</p>
<p>
<label for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" />
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" />
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>

In this form, first, last, username, password, confirmation password, and email. They are all non-null, and the email needs to be properly formatted with the address, confirmation password, and password 1 sent. The easiest way to verify using jQuery is to introduce two js files, jquery.js and jquery validation.js. Then class was added to input respectively, that is:


<input id="firstname" name="firstname" class="required"/>
<input id="lastname" name="lastname" class="required"/>
<input id="username" name="username" class="required"/>
<input id="password" name="password" type="password" class="required"/>
<input id="confirm_password" name="confirm_password" type="password" class="required" equalTo="#password"/>
<input id="email" name="email" class="required email"/>

The default validation that comes with validate is listed below

required: "Required fields ",
remote: "Please correct this field ",
email: "Please enter the correct email format ",
url: "Please enter a valid url ",
date: "Please enter a valid date ",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number ",
digits: "Integer only ",
creditcard: "Please enter a valid credit card number ",
equalTo: "Please enter the same value again ",
accept: "Please enter a string with a valid suffix name ",
maxlength: jQuery.format (" Please enter 1 string of maximum length {0} "),
minlength: jQuery.format (" Please enter 1 string of at least {0} length "),
rangelength: jQuery.format (" Please enter 1 string of length between {0} and {1} "),
range: ES106en.format (" Please enter a value between {0} and {1} "),
max: ES110en.format (" Please enter 1 value of maximum {0} "),
min: ES114en.format (" Please enter a value with a minimum value of {0} ")

Then, in document's read event, add the following method:


   <script>
    $(document).ready(function(){
        $("#signupForm").validate();
    }
   </script>

This way, when form is submitted, it is validated against the class specified by input. If this fails, the form submission will be blocked. Also, the prompt is displayed after input.

However, this doesn't feel good because the validation rules are breaking into our html code. Another way is to use "rules". We removed those input validations with class. Then modify the ready event response code for document:


$(document).ready(function(){
$("#signupForm").validate({
rules:{
firstname:"required",
lastname:"required",
username:"required",
password:"required",
confirm_password:{
required:true,
equalTo:"#password"
},
email:{
required:true,
email:true
}
}
});
})

In this way, the same effect can be achieved.

So, the next problem is that the error message is displayed by default. We need to use a custom prompt:


$(document).ready(function(){
$("#signupForm").validate({
rules:{
firstname:"required",
lastname:"required",
username:"required",
password:"required",
confirm_password:{
required:true,
equalTo:"#password"
},
email:{
required:true,
email:true
}
},
messages:{
firstname:" mandatory ",
lastname:" mandatory ",
username:" mandatory ",
password:" mandatory ",
confirm_password:{
required:" mandatory ",
equalTo:" The password is not 1 to "
},
email:{
required:" mandatory ",
email:" The format is wrong "
}
}
});
})

If you also want to display a special style (such as red font) on the error message, you can do so by adding:


<style type="text/css">
#signupForm label.error {
padding-left: 16px;
margin-left: 2px;
color:red;
background: url(img/unchecked.gif) no-repeat 0px 0px;
}
</style>

Continue to add validation rules for input password length:


$(document).ready(function(){
$("#signupForm").validate({
rules:{
firstname:"required",
lastname:"required",
username:"required",
password:{
required:true,
minlength:4,
maxlength:15
},
confirm_password:{
required:true,
equalTo:"#password"
},
email:{
required:true,
email:true
}
},
messages:{
firstname:" mandatory ",
lastname:" mandatory ",
username:" mandatory ",
password:{
required:" mandatory ",
minlength:jQuery.format(" Password length not less than {0} position "),
maxlength:jQuery.format(" The password length should not exceed {0} position ")
},
confirm_password:{
required:" mandatory ",
equalTo:" The password is not 1 to "
},
email:{
required:" mandatory ",
email:" The format is wrong "
}
}
});
})

Using remote

event can be used to specify the trigger effect mode (keyup(each keystroke), blur(when the control loses focus), or only triggered when the submit button is not specified).


$(document).ready(function(){
$("#signupForm").validate({
event:"keyup" || "blur"
})
})

If you specify debug as true, the form will not be submitted and can only be used for validation (submit by default), which can be used for debugging


$(document).ready(function(){
$("#signupForm").validate({
debug:true
})
})

Use the submitHandler parameter if you need to do some custom processing before committing


<form id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" class="required"/>
</p>
<p>
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" />
</p>
<p>
<label for="username">Username</label>
<input id="username" name="username" />
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password" />
</p>
<p>
<label for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" />
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" />
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
0

Related articles: