神刀安全网

Manually use ASP.NET MVC's client side validation

ASP.NET MVC client side validation is based on the jQuery validation plugin. It can be said that MVC’s client-side validation is an opinionated version of how jQuery validation should work in an ASP.NET MVC project. Despite this, the underlying implementation is fully based on jQuery’s. In this blog post I’ll show you how you can take advantage of this.

Manually use ASP.NET MVC's client side validation

ASP.NET MVC Client Side validation requirements

First, here’s the list of things you need to do to enable client-side validation in an ASP.NET MVC project Make sure your client side code is loading both:

  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure your web.config has the following keys in appSettings with the follwoing values:

  <appSettings>     ...     <add key="ClientValidationEnabled" value="true" />     <add key="UnobtrusiveJavaScriptEnabled" value="true" />   </appSettings> 

These settings can be overridden in a controller, make sure that is not happening. For example this would turn off client side validation if executed inside a controller’s action:

public ActionResult Index() {     HtmlHelper.ClientValidationEnabled = false;         return View(); } 

The next requirement is that you use attributes from System.ComponentModel.DataAnnotations in the Model class that is used in view where you want client-side validation enabled.

For example, if we want the Email field to be a valid email, and make the password and email fields required we would create a model like this:

using System.ComponentModel.DataAnnotations;   public class LoginViewModel {     [Required]             [EmailAddress]     public string Email { get; set; }      [Required]                     public string Password { get; set; }             } 

Finally, we have to use the HtmlHelpers that generate the correct markup for all of this to work, and they have to be inside a form, for example

@model LoginViewModel  <form>     @Html.LabelFor(m => m.Email)     @Html.TextBoxFor(m => m.Email)     @Html.ValidationMessageFor(m => m.Email)      @Html.LabelFor(m => m.Password)     @Html.PasswordFor(m => m.Password)     @Html.ValidationMessageFor(m => m.Password) </form> 

Getting away with using Client Side validation without a model

The last two requirements are actually optional. It is possible to take advantage of client side validation without having to create a model class and annotate it, which can be useful if you only use a couple of parameters (such as in the Login example).

If you inspect the markup that the helpers generate you’ll see that it’s actually pretty simple:

<input type="text" name="email" data-val="true" data-val-required="The email is required"/> <span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace="true"></span> 

It turns out that to enable client side validation without using the HtmlHelpers and a model you just have to add an input with data-val="true" and then data-val- followed by validation method that you want to apply (e.g. data-val-required ), the value of which will be the error message presented to the user (e.g. data-val-required="This is the error message" ). This works because the MVC’s “unobtrusive validation” works by looking for inputs that are annotated with data-val attributes.

The data-valmsg-for ‘s value is the name (not the id ) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field:

<span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace="true">The email must be unique</span> 

This message would then be replaced by any validation error that occurs in the email field, for example “The email is required”. If data-valmsg-replace="false" then the original message will never be replaced. The only consequence of an error is that the span’s class is changed from field-validation-valid to field-validation-error (this happens irrespectively of the value of data-valmsg-replace="false" ).

Some validation methods have parameters, for example RegularExpression . The way these work is very similar, they just need additional data-val- for their parameters. If you want to validate a text field using a regular expression for 5 to 8 digits, it would look like this:

<input type="text" name="number" id="number" data-val="true" data-val-regex="Valid input is 5 to 8 digits" data-val-regex-pattern="^/d{5,8}$"/> 

If you create the markup yourself you can get away without having to create a model for your view. Using the login example from above, your controller action for handling the user logging in could simply be:

    public ActionResult Login(string email, string password)     {                    ...     } 

You’d have to make any server-side checks on the parameters yourself though.

Here is the list of the System.ComponentModel.DataAnnotation attributes you can use, and their data-val counterparts:

  • Compare
    • data-val-equalto="Error message"
    • data-val-equalto-other="The name of the other field"
  • CreditCard
    • data-val-creditcard="Error message"
  • EmailAddress
    • data-val-email="Error message"
  • MaxLength
    • data-val-maxlength="Error message"
    • data-val-maxlength-max="Maximum length (e.g. 5)"
  • MinLength
    • data-val-minlength="Error message"
    • data-val-minlength-min="Minimum length (e.g. 2)"
  • Range
    • data-val-range="Error message"
    • data-val-range-max="Max value"
    • data-val-range-min="Min value"
  • RegularExpression
    • data-val-regex="Error message"
    • data-val-regex-pattern="The regular expression (e.g. ^[a-z]+$)"
  • Required
    • data-val-required="Error message"
  • StringLength
    • data-val-length="Error message"
    • data-val-length-max="Maximum number of characters"

There are also a few validation methods you can use that don’t seem to have a counterpart in System.ComponentModel.DataAnnotation . In fact you get a list of all the available client side validation methods by typing (for example in chrome) dev tools console: $.validator.unobtrusive.adapters . Here’s the list of the ones that don’t have a matching attribute: date, digits, number, url, length, remote, password .

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Manually use ASP.NET MVC's client side validation

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮