This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging

JQuery validation and limitations

JQuery validation and limitations

Bind keyboard listening events


    $(document).on("keypress", ".txt-valid-len", function (e) 
	{
		return (this.value.length < $(this).attr("maxlength"));
	});

Copy the code

Input box Settings

  • Then we just need to add the txt-valid-len class attribute to the input. Add the maxLength attribute to specify the length.

<input type="text" id="user_name" name="name" class="form-control txt-valid-len" maxlength="11" />
Copy the code
  • The above code means that the input field is limited to 11 bits in length, and will not be displayed after 11 bits. If you want to indicate more than 11 bits. You can extend the above listener events.

Jquery form submission validation

  • In development, we often need to verify the relevant data in front of the interaction with the background. This reduces stress on the server. Let’s take a look at the methods jquery provides for form validation.

Importing script Files

jquery.min.js
jquery.validate.js
Copy the code
  • These two js are included in the official website of jQuery, directly download and introduce the line.

  • With these two Js’s we also need the form form on the page. The form is our normal form.

<form id=" myForm "method="post" action="#"> <p> <label ="myname"> --> <input id="myname" name="myname" /> </p> <p> <label for="age"> < / label > < input id = "age" name = "age" / > < / p > < p > < label for = "email" > E - Mail: </label> <input id="email" name="email" /> </p> <p> <label for="password"> <input id="password" name="password" type="password" /> </p> <p> <label for="confirm_password"> </label> <input name="confirm_password" type="password" /> </p> <p> <input class="submit" type="submit" value=" Register "/> </p> </form>Copy the code

Custom JS form validation (using jQuery to provide built-in methods)

  • First we use the selector provided by jQuery to find the form we need to validate
$("#myform").validate();
Copy the code
  • This completes form validation. Of course, it’s just the shelves are ready. Let’s enter our validation rule in validate.
$("# myForm ").validate({debug: true, //errorClass: "Label. error", // The default style class is: error focusInvalid: false, // When false, there is no focus response when validation is invalid onKEYup: false, submitHandler: Function (form){// Form alert(" submit form "); form.submit(); }, rules:{myname:{required:function(element){if($("#age").val() < 13){return true; } else{ return false; }}}, email:{required:true, email:true}, password:{required:true, rangelength:[3,10]}, Confirm_password :{equalTo:"input[name=password]"}}, messages:{myname:{required:" required "}, email:{ required:"<span style='color:red; '> Only integers are allowed. < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 21px; font-size: 14px! Important; white-space: normal;" )}, confirm_password:{equalTo:" two password inputs are different "}}});Copy the code
  • Where rules is the content of our validation rules. The myname, email… Is the value of the control’s name attribute (not its ID attribute) that our form needs to validate, and our prompt can be a little more fancy and styled
<span style='color:red; '> Only integers are allowed. </span>Copy the code
  • The validation rules can be found in jquery-validation.js. We can use the messages attribute for validation.

Dynamically determine validation rules

  • Myname required (id=age); myname required (id=age); myname required (id=age); Greater than the opposite. If you want to make it more glamorized we can bind the age input to a blur that loses focus. After the age is entered we immediately validate the myName input rule by calling
$("#myname").valid();
Copy the code
  • We will verify the input value of the myName field according to our rules.

Verification is performed remotely

The front desk

  • Modify the above as follows, where remote is our remote request. If the request returns true, the authentication is successful, and false is otherwise.
$("#myform").validate({  
  rules: {  
    email: {  
      required: true,
      email: true,
      remote: {
          type:"post",
          dataType: "json",
          contentType : "application/json",
          url:"/adminManage/email.bsh"
      }  
    }  
  }  
}); 
Copy the code

The background

  • Note that the request format for remote has some requirements. The data returned by this URL must be in JSON format. The background value can only be string or Boolean. If the string is true then the validation is successful. If the string is not true then the validation prompt is the string you returned. If it is Boolean, the validation succeeds if it is true; if it is false, the validation fails.
@RequestMapping("/email.bsh") @ResponseBody public Object email(HttpServletRequest request,HttpServletResponse response) {return "already exists "; }Copy the code
  • The foreground prompt already exists. The default foreground prompt will be overwritten
@RequestMapping("/email.bsh") @ResponseBody public Object email(HttpServletRequest request,HttpServletResponse response)  { return "true"; }Copy the code
  • Verification by
@RequestMapping("/email.bsh") @ResponseBody public Object email(HttpServletRequest request,HttpServletResponse response)  { return true; }Copy the code
  • Verification by
@RequestMapping("/email.bsh") @ResponseBody public Object email(HttpServletRequest request,HttpServletResponse response)  { return false; }Copy the code
  • If the authentication fails, the default message is displayed

Refer to the website

Verify the display location of the prompt

  • In the previous section we detailed the rules and hint implementation for validation. Then the location of the prompt message is sometimes very important, we control the good interface will be very beautiful.
Var validator = $("# myForm ").validate({debug: true, // errorClass: "Haha ",// default is error focusInvalid: false, onkeyup: false, submitHandler: Function (form){// Form alert(" submit form "); //form.submit(); Username: {required: true, minlength: 2, remote: {required: true, minlength: 2, remote: }, firstPwd: {required: true, // minLength: 6 rangelength: [6,8]}, secondpwd: {required: true, equalTo: "#password"}, sex: {required: true}, age: {required: true, range: [0,120]}, Email: { required: true, email: true }, purl: { required: true, url: true }, afile: { required: true, accept: "XLS,doc,rar,zip"}}, messages: {username: {required:" Username is required! , minlength: $. Format (" The username must be at least {0} characters! ") ), remote: $.format("{0} already occupied ")}, firstpwd: {required: "Password is required!" , rangelength: $. Format (" Password must be between {0}-{1} characters! ") )}, secondpwd: {required: "Password authentication is required!" , equalTo: "Password authentication must be the same as password"}, sex: {required: "gender is required"}, age: {required: "age is required ", range:" age must be between {0}-{1} "}, email: {required: "Email is required!" , email: "Please enter a correct email address (such as [email protected])"}, purl: {required: "Personal home page is required ", URL: "Please input the correct url format, such as http://www.domainname.com"}, afile: {required: "attachment is necessary!" , Accept: "only accept XLS, Doc, RAR, ZIP files"}}, errorPlacement: AppendTo (element. Parent ("td").next("td")); function(error, element) {// validate where the message is placed error.appendto (element.parent("td").next("td")); }, highlight: function(element, errorClass) {$(element).addClass(errorClass); }, success: function(label) { label.addClass("valid").text("Ok!" )} /*, errorContainer: "#error_con", // Validates the container to be placed in the message set errorLabelContainer: "#error_con ul", // The wrapper to hold the unordered list of messages: ErrorElement: "em", // Validates the label name, defaults to: label Success: "Valid" // Valid style class */});Copy the code

Refactoring rules

Whenever multiple fields in your form contain the same validation rules and validation messages, refactoring rules can reduce a lot of duplication. Using addMethod and addClassRules can be very effective. Suppose the following rules have been refactored:

// alias required to cRequired with new message  
$.validator.addMethod("cRequired", $.validator.methods.required,  
  "Customer name required");  
// alias minlength, too  
$.validator.addMethod("cMinlength", $.validator.methods.minlength,   
  // leverage parameter replacement for minlength, {0} gets replaced with 2  
  $.format("Customer name must have at least {0} characters"));  
// combine them both, including the parameter for minlength  
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 }); 

<input name="customer1" class="customer" />  
<input name="customer2" class="customer" />  
<input name="customer3" class="customer" /> 
Copy the code

adMethod

AddMethod (name, method, [message]) returns: undefined

Parameter name type: String The name of the method to be added for identification and reference, which must be a valid javascript identifier.

Parameter method type: Callback is the implementation part of the method, which returns true if the form element passes validation.

Parameter Message (Optional) type: String, Function Specifies the default validation message for this method. This can be created using the jQuery.validator.format(value) method. If this parameter is not defined, the validation message that already exists locally is used, and in addition, the validation message must be defined for the specified form element.

Description: Add a user – defined validation method. It consists of the method name (which must be a valid javascript identifier), the javask-based function, and the default validation message.

AddClassRules (name, rules) returns: undefined

Parameter name Type: String Name of the style rule to add.

Parameter rules Type: Options Indicates the rule Options.

Description: Adds a composite style validation method. This is useful for refactoring multiple rules that are used in combination into a single style.