MVC validation 02-Custom validation rules, message validation

Source: Internet
Author: User

Original: MVC validation 02-Custom validation rules, message validation

This article experiences the MVC custom validation feature to enable validation of messages. For custom validation attributes that have just been written, back-end validation is only supported at first. If you want to have front-end jquery support, you must also extend the validation of jquery.

This article is related to "MVC authentication 01-BASIC, Remote Authentication" and, if necessary, please refer to.

When we verify the properties of the email, we may write:

[RegularExpression (@ "\w.+\@\w.+")]
 Public string Email {get; set;}

This only takes into account the @ symbol, but that's not enough, and we might write:

[RegularExpression (@ "^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$ ")]
 Public string Email {get; set;}

This is slightly "bloated", in fact, we can extend the ValidateAttribute feature of MVC to "one package, multiple use".

Custom validation Attributes

ExpandusingSystem.ComponentModel.DataAnnotations;usingSystem.Text.RegularExpressions;namespacemvcvalidation.extension{ Public Sealed classEmailattribute:validationattribute { Public Const stringReg = @ "^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$"; PublicEmailattribute () {}//overriding base class methods         Public Override BOOLIsValid (Object value)        {if(value==NULL)return true;if(value  is string) {Regex regex =NewRegex (REG);returnRegex.IsMatch (value.            ToString ()); }return false; }    }}

Attention:
Declare your custom extension class as sealed class.
The regular expression that validates the message here is not necessarily the perfect one.

Where custom features are useful: View model

ExpandusingMvcvalidation.extension; Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")] [Remote ("Checkusername","Validate", errormessage ="Remote authentication of user name failed")] Public stringUserName {Get;Set; } [Required] [DataType (datatype.emailaddress)] [Display (Name = "Mail")] [Email] Public stringEmail {Get;Set; } [Required] [stringlength (errormessage = "{ 0} field minimum {2} characters, up to {1} characters", Minimumlength = 6)] [DataType (Datatype.password)] [Display (Name ="Password")] Public stringPassword {Get;Set; } [DataType (Datatype.password)] [Display (Name = "Confirm Password")] [System.ComponentModel.DataAnnotations.Compare ("Password", errormessage ="The password and confirmation password do not match. ")] Public stringConfirmPassword {Get;Set; }    }

Register.cshtml

Expand@model mvcvalidation.models.registermodel@{viewbag.title = "Register";} class="title> using(Html.BeginForm ())        {@Html. AntiForgeryToken () @Html. ValidationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @Html. labelfor (M = m.username) @Html. Textboxfor (M                + m.username) </li> <li> @Html. labelfor (M = m.email) @Html. textboxfor (M = m.email) </li> <li> @Html. labelfor (M = M.                Password) @Html. passwordfor (M = m.password) </li> <li> @Html. labelfor (M = M.confirmpassword) @Html. passwordfor (M = m.confirmpassword) </li&        Gt </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval")}

Effect:

Attention:
The custom validation feature at this time only supports back-end validation, and if you want to support front-end jquery validation, you need to implement the Iclientvalidatable interface.

Custom attributes implement the Iclientvalidatable interface to prepare for jquery validation

ExpandusingSystem.ComponentModel.DataAnnotations;usingSystem.Text.RegularExpressions;usingSYSTEM.WEB.MVC;namespacemvcvalidation.extension{ Public Sealed classEmailattribute:validationattribute, iclientvalidatable { Public Const stringReg = @ "^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$"; PublicEmailattribute () {}//overriding base class methods         Public Override BOOLIsValid (Object value)        {if(value==NULL)return true;if(value  is string) {Regex regex =NewRegex (REG);returnRegex.IsMatch (value.            ToString ()); }return false; } PublicSystem.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context) {Modelclientvalidationrule rule =Newmodelclientvalidationrule {ValidationType = "Email", errormessage = formaterrormessage (metadata.            GetDisplayName ())}; YieldreturnRule }    }}

Attention:
The value of the ValidationType attribute must be lowercase, otherwise error.

Extend jquery to support custom extension features Emailattribute

JQuery.validator.email.js file:

Extension methods
$.validator.addmethod ("Email", function (value, Element) {
if (value = = False) {
return true;
}
This.optional (Element) | | /^[\w-]+ (\.[ \w-]+) *@ ([\w-]+\.) +[a-za-z]+$/i.test (value);
});

Extension method Registration
$.validator.unobtrusive.adapters.addbool ("email");

In order to implement jquery client authentication, the JS files required in the register.cshtml include:

1. Quoting Query-{version}.js
2. Quoting Jquery.validate.js
3. Quoting Jquery.validate.unobtrusive.js
4. Custom jquery Validation Extension

Because there is @scripts.render ("~/bundles/jquery") in _layout.cshtml, no references are required in all register.cshtml.
Register.cshtml contains @scripts.render ("~/bundles/jqueryval"), which means that references to 2 and 3 are included.
Register.cshtml also requires the introduction of jquery extension methods for custom attribute Emailattribute features.

The complete register.cshtml is as follows:

Expand@model mvcvalidation.models.registermodel@{viewbag.title = "Register";} class="title> using(Html.BeginForm ())        {@Html. AntiForgeryToken () @Html. ValidationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @Html. labelfor (M = m.username) @Html. Textboxfor (M                + m.username) </li> <li> @Html. labelfor (M = m.email) @Html. textboxfor (M = m.email) </li> <li> @Html. labelfor (M = M.                Password) @Html. passwordfor (M = m.password) </li> <li> @Html. labelfor (M = M.confirmpassword) @Html. passwordfor (M = m.confirmpassword) </li&        Gt </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src="~/scripts/jquery.validator.email.js"&GT;&LT;/SCRIPT&GT;}



Effect:


How do I confirm that the jquery validation mechanism is enabled?
Before implementing Iclientvalidatable, review the form elements for email as follows:

After implementing Iclientvalidatable, review the form elements for email as follows:

Visible, after implementing Iclientvalidatable, the Data-val-email attribute is more.


Attention:
jquery itself contains validation of email, and the validation of jquery is extended for demonstration purposes.

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: info-contact@alibabacloud.com 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.