asp.net mvc5+ef6+easyui background Management system (-MVC) Form validation __.net

Source: Internet
Author: User
Tags jquery library
Series Catalog

Note: This section of reading needs to have the basis of MVC custom validation, otherwise it is more laborious

All along, the verification of the form is indispensable, Microsoft's things still do more humane, from WebForm to MVC, have done a two-way authentication

Using JS alone to achieve the front-end verification is extremely unsafe, so this time we look at MVC on the self-annotated verification, custom validation

The same MVC provides a series of built-in data validation annotations are not NULL validation [Required (errormessage = "cannot be empty")] length validation [stringlength (minimumlength = 2)] Value range [ Range (1, 3)] Type validation [DataType (datatype.date)] Regular expression [RegularExpression (@) [a-za-z0-9._%+-]+@[a-za-z0-9.-]+/.[     a-za-z]{2,4} ")] Email Demo Remote authentication [remote (" Checkusernameexists "," Validationdemo ", errormessage =" User name already exists ")] Request validation [allowhtml] Allow incoming HTML, etc...

The login model classes that are MVC3 the project template are as follows:

public class Logonmodel
{
    [Required]
    [Display (Name = ' User name ']] public
    string UserName {get; set;}
 
    [Required]
    [DataType (Datatype.password)]
    [Display (Name = "Password")]
    public string Password {get; set;}
 
    [Display (Name = Remember me.) )] public
    bool RememberMe {get; Set }

MVC3 is already in the template project with:

<add key= "clientvalidationenabled" value= "true"/>
<add key= "unobtrusivejavascriptenabled" value= "true"/>
Then take a two javascript on the validated view page, which is attached to jquery:

<script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></ Script>
There are two types of validation messages, one is ValidationSummary, which displays a summary of the validation messages that contain the messages returned from the background action.

@Html. ValidationSummary (True, "Login was unsuccessful.) Please correct the errors and try again. )
The other is the validation message for each property in model corresponding to the HTML control:

@Html. Validationmessagefor (M => m.username)

So you have to introduce the jquery library for the front-end code to have validation effects

But often the system's own verification is far from satisfied with us, we need more flexible encapsulation, it is impossible I want to verify that the number is filled in between 0-9 to write a table expression bar, fortunately, the official also flexible to provide an extension, custom validation.

Custom validation I will not say more, search in the park on a lot of principles and writing methods. Here I share a common custom validation

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.ComponentModel.DataAnnotations;
Using SYSTEM.WEB.MVC;
Using System.Globalization;
Using System.Web.Security;


Using System.Text.RegularExpressions; Namespace App.models {/** use description * Inherit Validationattribute abstract class, rewrite IsValid () method to implement server-side validation * Implementation Iclientvali   The Getclientvalidationrules () method of the Datable interface to achieve client-side validation * 1.   [Intrangeexpression (18, 30)] The number between 18 and 30, can not be filled out, but fill in to enter the verification * 2.   [Maxwordsexpression (50)] The number of characters in can not be greater than 50, you can not fill in, but fill in to enter the verification * 3.   [Notnullexpression] verifies that it is empty and calls * 4.   [Dateexpression] is the date format: 2012-10-1 * 5.   [Ischarexpression] can only be numbers, letters, underscores, dashes, can not fill in * 6.   [Chinacharexpression] can only input Chinese characters, you may not fill in * 7.   [Notequalexpression ("ABCD")] cannot be equal to the specified value and can not be filled in: if not equal to ABCD * 8.      [Containexpression ("abc")]       Verify that the specified string is included and may not be filled in: if ABC * 9 must be included.   [Notcontainexpression ("abc")] verifies that a string cannot be specified, and can not be filled out, if it cannot contain ABC *10.   [Isintegerepression] verifies that the number format can be blank and can be 1,-5 *11 for any integer.   [Ispositiveintegerexpression] verifies that the number format is not filled in, and must be any positive integer 25 *12.   [Isnegativeintegerexpression] verifies that the number format is not filled in, and must be any negative integer-25 *13.   [Isdecimalexpression] verifies that the number format can be blank and can be 12.12,12,-12.12 *14 for any floating-point numbers.   [Ispositivedecimalexpression] verifies that the number format can be blank, and can be an arbitrary floating point 1.4 *15.   [Isnegativedecimalexpression] verifies that the number format can be blank, and can be any negative floating-point number-1.2 *16.   [Emailexpression] Verify that it is an email *17. [Phoneexpression] Verify that the Chinese phone number such as: 0769-222222-222 the correct format is: "Xxx-xxxxxxx", "xxxx-xxxxxxxx", "xxx-xxxxxxx", "X
        Xx-xxxxxxxx "," XXXXXXX "and" XXXXXXXX ".   *18.   [Siteexpression] Verify that it is a complete URL such as: www.163.com *19. [Isnumberexpression] ValidationWhether it is a number format can not be filled out, can be any number * * * * Combined with demo * [DisplayName ("name")] Name
        * [notnullexpression] cannot be empty * [Maxwordsexpression (50)] up to 50 characters, 25 characters               * [Ischarexpression] can only be made up of numbers, letters, underscores, underscores (typically used to validate IDs) * [Notequalexpression ("admin")]
        Cannot package contains admin String * public string Id {get; set;}  * * Digital Judgment Demo * [Isnumberexpression] can not fill out, fill out the judge is the number * [DisplayName ("code")] * public int?
        Age {get; set;} * Non-null word use *//[required (Errormessageresourcetype = typeof (Errorrs), errormessageresourcename = "isnumberexpression ")] * or//[required (errormessage=" must fill in this field ")] to overwrite localization such as public int age; int? For nullable word end **////<summary>///[Intrangeexpression (18, 30)] number between 18 and 30, can not fill in, but fill in to enter validation///< /summary> public class Intrangeexpressionattribute:validationattribute, Iclientvalidatable {long minmum {get; set;}
        Long Maxmum {get; set;}
            Public Intrangeexpressionattribute (long minimum, long maximum) {minmum = minimum;
        Maxmum = maximum; public override bool IsValid (object value) {if (value = = null) return True
            ;
            Long intvalue = Convert.toint64 (value);
        return intvalue >= minmum && intvalue <= maxmum; Override string Formaterrormessage (string name) {return String.Format (cultureinfo.c
        Urrentculture, "{0} must be between {1} and {2}", Name, Minmum, maxmum); Public ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, Controller
            Context context) {Modelclientvalidationrule validationRule = new Modelclientvalidationrule ()
    {ValidationType = "Isinteger",            ErrorMessage = formaterrormessage (metadata.
            DisplayName)};
            Validate the code passing parameters to the client validationRule.ValidationParameters.Add ("param1", minmum);
            VALIDATIONRULE.VALIDATIONPARAMETERS.ADD ("param2", maxmum);
        Yield return validationRule; }///<summary>///[Maxwordsexpression (50)] The number of characters in the can not be large 50, you can not fill in, but fill in to enter the validation///</summary> PU
        Blic class Maxwordsexpressionattribute:validationattribute, iclientvalidatable {int maxstr {get; set;}
        public maxwordsexpressionattribute (int maximum) {maxstr = maximum; public override bool IsValid (object value) {if (value = = null) return True
            ; String valueasstring = value.

            ToString ();

        Return (Encoding.Default.GetByteCount (valueasstring) <= maxstr);
        public override string Formaterrormessage (string name) {    Return String.Format (CultureInfo.CurrentCulture, "{0} up to {1} characters, {2} characters", Name, MAXSTR/2, MAXSTR); Public ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, Cont
            Rollercontext context) {Modelclientvalidationrule validationRule = new Modelclientvalidationrule () {ValidationType = "maxwords", errormessage = formaterrormessage (metadata.
            DisplayName)};
            VALIDATIONRULE.VALIDATIONPARAMETERS.ADD ("param", maxstr);
        Yield return validationRule;
    }///<summary>///[Minwordsexpression (50)] characters cannot be less than 50 characters, can not be filled out, but fill in to enter validation///</summary> public class Minwordsexpressionattribute:validationattribute, iclientvalidatable {int minstr {get; set ;
        public minwordsexpressionattribute (int minimum) {minstr = minimum; } Public override bool IsValid (object value) {if (value = = null) return true; String valueasstring = value.

            ToString ();

        Return (Encoding.Default.GetByteCount (valueasstring) >= minstr); Override string Formaterrormessage (string name) {return String.Format (cultureinfo.c

        Urrentculture, "{0} at least {1} characters", name, MINSTR); Public ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, ControllerC
            Ontext context) {Modelclientvalidationrule validationRule = new Modelclientvalidationrule () {ValidationType = "minwords", errormessage = formaterrormessage (metadata.
            DisplayName)};
            VALIDATIONRULE.VALIDATIONPARAMETERS.ADD ("param", minstr);
        Yield return validationRule; }}///<summary>///[notnullexpression]Verify that it is empty and cannot have a free style with///</summary> public class Notnullexpressionattribute:validationattribute, Iclientvalidat
        Able {static string dispalyname = ""; Public Notnullexpressionattribute (): Base ("{0} must be filled in") {} public override string forma
        Terrormessage (string name) {return String.Format (name, dispalyname);
                public override bool IsValid (object value) {if (value = = null) {
            return false; String valueasstring = value.
            ToString (); BOOL result =!string.
            IsNullOrEmpty (valueasstring);

        return result; Public ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, Controller Context context) {Dispalyname = metadata.
            DisplayName; return new[]{new Modelclientvalidationrequiredrule (FormaterrormessaGE ("{0} must be filled in"))}; }///<summary>///[dateexpression] is a date format: 2012-10-1///</summary> public class Dat Eexpressionattribute:regularexpressionattribute, iclientvalidatable {static string regstr = @ "(^ (1[8-9]\d {2}) | ([2-9]\d{3})] ([-\/\._]) (10|12|0?) [13578]) ([-\/\._]) (3[01]| [12] [0-9]|0? [1-9]) $)| (^ (1[8-9]\d{2}) | ([2-9]\d{3})] ([-\/\._]) (11|0?) [469]) ([-\/\._]) (30| [12] [0-9]|0? [1-9]) $)| (^ (1[8-9]\d{2}) | ([2-9]\d{3})] ([-\/\._]) (0?2) ([-\/\._]) (2[0-8]|1[0-9]|0?) [1-9]) $)| (^ ([2468][048]00) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([3579][26]00) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([1][89][0][48]) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([2-9][0-9][0][48]) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([1][89][2468][048]) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([2-9][0-9][2468][048]) ([-\/\._]) (0?2) ([-\/\._]) (29) $) | (^ ([1][89][13579][26]) ([-\/\._]) (0?2) ([-\/\._]) (29) $) |
        (^ ([2-9][0-9][13579][26]) ([-\/\._]) (0?2) ([-\/\._]) (29) $)) ";
 Public Dateexpressionattribute ()           : Base (REGSTR) {} public override bool IsValid (object value) {I
            F (value = = null) return true;
            Regex reg = new regex (REGSTR); String valueasstring = value.
            ToString ();
            String Dtvalue; if (value. ToString (). IndexOf ("") > 0) {dtvalue = Valueasstring.replace ("/", "-").
            Substring (0, Valueasstring.indexof (""));
            else {dtvalue = Valueasstring.replace ("/", "-"); Match MCH = Reg.
            Match (Dtvalue); if (MCH.
            Success) {return true;
            else {return false; Override string Formaterrormessage (string name) {return String.Format (Cul
        Tureinfo.currentculture, "{0} must be date format: 2012-10-10", name); } public Ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, ControllerContext Context) {var name = metadata.
            GetDisplayName ();
            var rule = new Modelclientvalidationregexrule (formaterrormessage (name), pattern);
        yield return rule; }///<summary>///[ischarexpression] can only be numbers, letters, underscores, underscores, can not fill///</summary> public c Lass Ischarexpressionattribute:regularexpressionattribute, iclientvalidatable {static string regstr = @ "^[0
        -9a-za-z_-]{0,}$ "; Public Ischarexpressionattribute (): Base (REGSTR) {} public override bool IsValid (o
            Bject value) {if (value = = null) return true;
            Regex reg = new regex (REGSTR); Match MCH = Reg. Match (value.
            ToString ()); if (MCH.
            Success) {return true;
          } else  {return false; Override string Formaterrormessage (string name) {return String.Format (Cul
        Tureinfo.currentculture, "{0} consists of letters, numbers, dashes, dashes", name); Public ienumerable<modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, Controller Context context) {var name = metadata.
            GetDisplayName ();
            var rule = new Modelclientvalidationregexrule (formaterrormessage (name), pattern);
        yield return rule; }///<summary>///[chinacharexpression] can only enter Chinese characters, you may not fill///</summary> public class Chin Acharexpressionattribute:regularexpressionattribute, iclientvalidatable {static string regstr = @ "^[\u4e00- \u9
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: 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.