Client-side validation of asp: jquery validation

Source: Internet
Author: User
Tags valid email address


The model validation we've been discussing before is limited to server-side validation, where the Web servers validate the request data against the appropriate rules. If we were able to validate the data entered by the user in the client (browser), this would reduce the frequency of requests to the server, thereby easing the stress on Web server access. Asp. MVC 2.0 and its previous versions were client-side verified with ASP. ASP 3.0, the jquery validation framework was introduced so that we could use unobtrusive JavaScript for client-side validation. [This article has been synced to ' how ASP. NET MVC Works ']

One, unobtrusive JavaScript
Ii. specifying validation rules in an inline manner
Iii. specifying validation rules and error messages separately

One, unobtrusive JavaScript

Unobtrusive JavaScript has become a guideline for javasccript programming, unobtrusive JavaScript embodies a mainstream web design strategy, "progressive enhancement (pe,progressive Enhancement) ". It uses a layered approach to the separation of Web page content and functionality, meaning that JavaScript for a function is not embedded in the HTML used to present the content, but rather as an independent hierarchy based on HTML.

Let's take validation as an example, there is a form in a Web page, and we need to validate the input to three text boxes (foo, bar, and Baz) in the form. Assuming that the specific validation operation is implemented in the Validate function, then we can use the following HTML when the corresponding text box in the loss of focus when the input data to implement validation.

   1: <form action= "/" >
   2:     <input id= "foo" type= "text" onblur= "Validate ()"/>
   3:     <input id= "bar" type= "text" onblur= "Validate ()"/>
   4:     <input id= "baz" type= "text" onblur= "Validate ()"/>
   5: ...     
   6: </form>

But this is not a good design, the ideal way is to let HTML only to define the structure of the content rendering, let the CSS control the content rendering style, and all the implementation of the functionality is defined in JavaScript, so the implementation of the validation of the JavaScript call should not appear in the HTML. So according to unobtrusive JavaScript programming, we should replace the inline-implemented event registration (onblur= "Validate ()") with the following form.

   1: <form action= "/" >
   2:   <input id= "foo" type= "text"/>
   3:   <input id= "bar" type= "text"/>
   4:   <input id= "baz" type= "text"/>
   5: </form>
   7: <script type= "Text/javascript" >
   2:     window.onload = function () {
   3:         document.getElementById ("foo"). onblur = Validate;
   4:         document.getElementById ("Bar"). onblur = Validate;
   5:         document.getElementById ("Baz"). onblur = Validate;

Unobtrusive JavaScript is a broad topic that is not likely to be introduced systematically in this article. Unobtrusive JavaScript is well represented in the validation of jquery, so let's briefly introduce the programmatic approach to validating with jquery.

Ii. specifying validation rules in an inline manner

The validation of jquery is actually validating the input elements that exist in the form, and it supports an inline (inline) programming approach where we can directly write the validation rules directly into the class (representing CSS type) attribute of the input HTML element being validated. Given that some readers may be unfamiliar with the validation framework for jquery, let's do a simple example validation.

While demonstrating jquery validation using a simple HTML file, here we create an empty web App with Visual Studio's ASP. NET MVC project template, which has two purposes: first, The. js file containing the jquery itself and its validation plug-in is automatically added to the project during the creation process, and the second is to ensure that the. js file that we are using for validation is consistent with the. js file that ASP. NET MVC really uses. We create the following default HomeController, which renders the default view in the action method index.

   1:public class Homecontroller:controller
   2: {
   3: Public     actionresult Index ()
   4:     {
   5:         return View (New contact ());
   6:     }

We will define the entire HTML as the rendering Web page in the view corresponding to the action method, as shown in the code snippet as the definition of the view. Since we use view to define the complete HTML for the final rendering, we set the layout to null.

   1: @{
   2:     Layout = null;
   4: <! DOCTYPE html>
   7: <link href= "@System. WEB.OPTIMIZATION.BUNDLETABLE.BUNDLES.RESOLVEBUNDLEURL (" ~/content/css ")" rel= "stylesheet "Type=" Text/css "/>
   8:     <script type= "Text/javascript" src= "Http://" ></script >
   2:     <script type= "Text/javascript" src= "Http://"/>
   3:     <script type= "Text/javascript" >
   4:         $ (document). Ready (function () {
   5:             $ ("form"). Validate ();
   6:             $ ("Td:first-child"). CSS ("text-align", "right");
   7:         });
   9:     <style type= "Text/css" >
  Ten:         label.error{color:red;}
  One:     </style>
  :     <title>Index</title>
  : <body>
  :     <form action= "/" >
  :     <table>
  :         <tr>
  :             <td> Name:</td>
  :             <td><input class= "required"  id= "name" name= "name" type= "text"/></td>
  :         </tr>
  :         <tr>
  :             <td> Date of birth:</td>
  Page:             <td><input class= "Required Date" id= "Birhthdate" name= "birhthdate" type= "text"/></td>
  :         </tr>
  :         <tr>
  :             <td>blog Address:</td>
  :             <td><input class= "required url" id= "blogaddress" name= "blogaddress" type= "text"/></td>
  :         </tr>
  £ º         <tr>
  :             <td>email Address:</td>
  To:             <td><input class= "required email" id= "EmailAddress" name= "EmailAddress" type= "text"/></td >
  :         </tr>
  :         <tr>
  :             <td colspan= "2" ><input type= "Submit" value= "Save"/></td>
  :         </tr>
  :     </table>
  Panax Notoginseng:     </form>
  : </body>

In addition to applying and manually defining styles via CSS files (label.error{color:red;} ), we need to include two necessary. js files, one is the core file of jquery Jquery-1.6.2.js, and the other is the jquery.validate.js to implement validation. The main part of the whole HTML file is a form, we can enter some personal information (name, date of birth, blog address and email address) through the text box, and then click "Save" button to submit the input data.

For the <input> elements of these four text boxes, the class attribute is used here to define the validation rules . where required indicates that the corresponding data is required, and date, url, and email verify the format of the input data to ensure it is a valid date, URL, and email address . The actual validation of the input is reflected in the following JavaScript call, where we are merely invoking the Validate method of the <form> element.

   1: <script type= "Text/javascript" >
   2:     $ (document). Ready (function () {
   3:         $ ("form"). Validate ();
   4:     });

Now run our program, a page for submitting personal information will be presented. When we enter illegal data, the corresponding error message appears on the right side of the element being validated, as shown in the effect.

Iii. Specifying validation rules and error messages separately

Validation rules can actually be defined in the validated HTML element without being inline, and can be defined directly in the Validate method used to implement validation. This method can specify not only the validation rules corresponding to the input elements validated by the form, but also the validation messages and other validation behaviors. Now we modify the HTML of the view shown in the example above to remove the four text boxes contained in the form from the validation rules set by the Class property . The Validate method is then invoked to implement validation by manually specifying the appropriate validation rules and error messages for the validated input elements as follows, and the validation rules and error messages are associated with the validation element through the name attribute (not the id attribute).

   1: <script type= "Text/javascript" >
   2:     $ (document). Ready (function () {
   3:         $ ("form"). Validate ({
   4:             rules   : {
   5:                 name        : {required:true},
   6:                 birhthdate  : {required:true, date:true},
   7:                 blogaddress: {url:true},
   8:                 emailaddress:{required:true, Email:true}
   9:             },
  One:             messages: {
  :                 name        : {required: "Please enter name"},
  Birhthdate:  {required: "Please enter the date of birth", Date: "Please enter a valid date"},
  Blogaddress:                 {url: "Please enter a valid URL"},
  emailaddress:{required: "                 Please enter your email address", Email: "Please enter a valid email address"}
  :             }           
  :         });
  :     });

To run our program again, our custom error messages will be rendered as shown in 6-9. (S612)

Client-side validation of asp: jquery validation
Client-side validation of asp: implementation of jquery validation in model validation
Client-side validation of asp: custom validation

Client-side validation of asp: jquery validation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.