The use of Jquery.Form and jquery.validate

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Some features require us to use Ajax technology POST submission form, then need to use jquery.Form, it has two ways to submit, AjaxForm and AjaxSubmit.

          AjaxForm MethodsYou must first bind the form, it is generally in the $(document).Ready (function () {} to the target POST definition, it can make the form does not refresh the page case. Such as:                    $(document).ready(function () {                  $("#UpdateForm").ajaxForm(function(){                          Alert(“AjaxForm submit completed”)                  });         }

AjaxSubmitMethodsSubmit the form to the corresponding event is through Ajax, submit such as click a button to trigger the form

Such as:

$(“#btnTest”).click(function(){          $("#UpdateForm").AjaxSubmit (function(){                 Alert(“AjaxForm submit completed”)         }); }) A description, parameters 1)BeforeSubmit

The BeforeSubmit parameter is used to verify the legitimacy in the form submitted to the data before Server, if the callback submitted prior to the implementation of the return False, the submission of the form will be terminated.

2)Success     The Success parameter form is submitted after the completion of execution Two, the API interface specification 1) FormSerialize Will form sequence into the query string. This method returns a type such as: name1=value1& name2=value2 string. Such as:                     var queryString = $('# myFormId).formSerialize(); Equivalent to the VaR queryString = $.param (formData) method of the two methods return values are the same 2) fieldSerialize Will the form element sequence into the string. When you only need to use this method to some elements form serialization. This method returns a type such as: name1=value1& name2=value2 string. Var queryString = $('#myFormId).FieldSerialize (.SpecialFields'); specialFields is the element of the Class value 3) fieldValue Remove all the matching requirements of the domain value, returns to the array. From the beginning of the 0.91 version, this method always returns an array. If you do not meet the conditions of the domain, the array would be an empty array, otherwise it will contain at least one value.                     var value = $('# myFormId':password').fieldValue();           alert('The password is: ' + value[0]); 4) resetForm By calling methods form elements inside DOM to reset to the initial state of the form. $('#myFormId').resetForm(); 5) clearForm Empty form the value of all the elements. This method will clear all text box, the password box, the text field value in the drop-down list, remove all the selected item, let all the checkboxes and radio buttons in the selected item is not selected. $('#myFormId').clearForm(); 6) clearFields Empty a form field values. This can be used in only need to clear the form part of the value of the element. $('#myFormId).ClearFields (.SpecialFields'); specialFields is the element of the Class value Three, Server end return form processing 1)JsonFormat

In setting the return Json format, to set the DataType format Option are as follows

dataType: 'json', JS successfully to the Server client code: if (ModelState.IsValid) {     return Json(new { a = "a", b = "b" }); }

After the Form to complete the success method will be executed, the responseText and responseXML values will be in this parameter (this depends on the type of dataType)

success: function (responseText, statusText, xhr, $form) {                 alert(responseText.a);             } 2)XMLFormat

In setting the return XML format, to set the DataType format Option are as follows

dataType: 'xml', JS successfully to the Server side code: // returns a XML of type string xmlString = "<1.0\" version=\? XML "encoding=\" gb2312\ "> <tree? Id=\" 0\ "> <item text=\" welcome to Beijing\"/></tree>";   return this.Content(xmlString, "text/xml");

After the Form to complete the success method will be executed

success: function (responseText, statusText, xhr, $form) {                   alert(xhr.responseText)             } 3)HTMLFormat

In setting the return HTML format, to set the DataType format Option are as follows

dataType: ‘HTML’, JS successfully to the Server client code: string htmlString = "<div style=\"background:red\">Test<div>";             return Content(htmlString);

After the Form to complete the success method will be executed

success: function (responseText, statusText, xhr, $form) {                   alert(responseText)             }

jquery.validate Use

A, useJquery.ValidateVerification method $(document).ready(function () {         $("#pageForm").validate({             rules: {                 DictKey: { required: true, maxlength: 10 },                 DictContent: { required: true, maxlength: 10 }             },             messages: {                 DictKey: { required: "Can not be empty ", maxlength: jQuery.format (" cannot exceed {0} characters") },                 DictContent: { required: "Can not be empty ", maxlength: jQuery.format (" cannot exceed {0} characters") }             },             submitHandler: function (form) {                 form.submit();             }         }) })

DictKey , DictContent: Refer to the validation controls ID

submitHandler : The function through the verification, write the function form to submit the form, otherwise will not submit

Two, list the commonly used default validation rules

(1)required:true              Required field
(2)email:true                 You must enter a correct email
(3)url:true                   You must enter the correct format.
(4)date:true                  You must enter the correct format date
(5)dateISO:true               You must enter the correct format date (ISO), for example: 2009-06-231998/01/22 only verify the format, do not verify the validity
(6)number:true                You must enter a valid number (negative numbers, decimal)
(7)digits:true                You must enter an integer
(8)creditcard:                You must enter a valid credit card number
(9)equalTo:"#field"          Must be the same as #field value input
(10)accept:                   String input has a legitimate extension (upload file suffix)
(11)maxlength:5               The input length is 5 characters (Chinese characters is one of the most character)
(12)minlength:10              Enter the minimum length is 10 characters (Chinese characters is a character)
(13)rangelength:[5,10]        The input length must be between the string "between 5 and 10 (Chinese characters) is a character)

(14)equalLength:10           The input length must be 10
(14)range:[5,10]              The input value must be between 5 and 10
(15)max:5                     The input value cannot be greater than 5
(16)min:10                    The input value of not less than 10

Three, the use ofajaxThe existence of validating input method. When the text box to enter the value, or to change the input value will automatically to the Server to verify the existence of the database in the JS code input values: DictKey: { required: true, maxlength: 10,                     remote: { //Verify that the user name is exist                         type: "POST",                         url: '@Url.Content("~/Account/Test/")' //servlet                                           }                 }, DictKey: { required: "Can not be empty ", maxlength: jQuery.format (" cannot exceed {0} characters "), remote:" user name has been registered"},

Server terminal:

[HttpPost]         public JsonResult Test(string DictKey) //DictKey is to verify the control's ID value         {             bool result;             if (DictKey == "a")             {                 result = true;             }             else             {                 result = false;             }             return Json(result);         }

According to the Server end back True, False decided to test whether the

Four, nonsubmitThe button combinationJquery.FormSubmit

If not submit the submit button, for example, click a button to trigger the form validation, then form validation available as follows

function validateForm() {    

//The validate method parameters are optional    

   return $("#form1").validate({    

       rules: {    

       },    

       messages:{   

      }

        }).form();    

}    

function doSubmit(){    

    //do other things    

    //Submit the verification through    

     if(validateForm()){    

        form.submit()    

//This can be combined with Jquery.FormAJaxSubmit asynchronous submission

         $("#UpdateForm").AjaxSubmit (function(){                          Alert(“AjaxForm submit completed”)                 });

    }  

}  

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Devin at November 26, 2013 - 6:16 AM