MVC Data validation

Source: Internet
Author: User
Tags valid email address

Controller Home

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using        Mvcapplication2.models;namespace mvcapplication2.controllers{public class Homecontroller:controller {//        GET:/home/public actionresult Index () {return View (); }///<summary>///Check if the user name is duplicated///</summary>//<param name= "UserName" > User Page (view) Form input username</param>///<returns>Json</returns> public ActionResult Checkusername        (String userName)            {bool result = false; using (var datas = new SalesEntities ()) {var query = from UserInfo in datas. T_userinfo where UserInfo. Name = = UserName Select new {name= userinfo.                Name}; if (query = = NULL | |!query.                Any ()) {result = true;     }                                 } return Json (Result,jsonrequestbehavior.allowget); }    }}

Model (UserInfo)

Using system;using system.collections.generic;using system.linq;using system.web;using System.ComponentModel;using System.componentmodel.dataannotations;using system.web.mvc;namespace mvcapplication2.models{//<summary>// /These examples are verified, note there is no client authentication, is fully server-side validation, if there is an error, the view will render again, very useful ah, very convenient ah, how many lines of code you have to write in the past to deal with these tedious and tasteless verification?    Microsoft is too sympathetic to programmers, the top one.    In the following example, when the data is sent to the server verification does not pass, then all users fill out the page after the re-opened empty, if you want to not empty, that is, the user first fill in the content is still there, you can return to View (the object received);        </summary> public class UserInfo {public int Id {get; set;}//id//<summary> DisplayName: Specifies the name of the current field display///stringlength: Specifies the allowable length, the first parameter in parentheses is the maximum length, and the second parameter is the minimum length. The last parameter is: the length of the single field value does not conform to the first second parameter, the content of the error///required: Indicates that the current field is a required option, and a validation error is raised when the submitted form is missing the value. The allowemptystrings in parentheses is: Gets or sets a value that indicates whether an empty string is allowed. A single value of FALSE indicates that the value of the current field cannot be null///remote: Allows the server-side callback function to execute the client's validation logic. To be blunt is to support Ajax validation. The checkusername in parentheses is the action method. Home is controller///</summary> [DisplayName ("username")] [Required (allowemptystringS=false, errormessage= "user name cannot be null")] [Stringlength (10,minimumlength=2,errormessage= user name cannot be greater than {2} and is less than {1}]] [Rem                OTE ("Checkusername", "Home", errormessage = "User name already exists")] public string UserName {get; set;}//user name        [DisplayName ("User password")] [DataType (Datatype.password)]//The password has * number form to display [Required (allowemptystrings=false,errormessage= "Password cannot be empty")] [stri        Nglength (12,minimumlength=6,errormessage= "Password must be between {2} and {1}")] public string UserPassword {get; set;}//user password        [DataType (Datatype.password)]        [Compare ("UserPassword", errormessage= "password Inconsistent")]  [DisplayName ("Please Confirm password again")] public string tuserpassword{get;set; Output password again///<summary>//RegularExpression: Indicates that the value of the current field conforms to a regular expression. If it does not match, a validation error is reported.        The errormessage content is the specific information that validates the error. </summary> [Display (Name = "Mailbox")]//can also be written as [DisplayName ("Mailbox")] [Required (allowemptystrings=false,e Rrormessage= "Mailbox cannot be empty")] [DataType (datatype.emailaddress,erRormessage= "Please enter a valid email address")//You can actually use the following regular expression to verify the mailbox//[regularexpression (@ "[a-za-z0-9._%+-][email protected][ A-za-z0-9]+\. [A-za-z]                {2,4} ", errormessage =" {0} is malformed ")] public string Email {get; set;}//Mailbox [DisplayName (" Please reconfirm mailbox ")] [Compare ("email", errormessage= "two times entered mailbox inconsistent")]//[datatype (datatype.emailaddress, errormessage = "Please enter a valid e-mail address" )] public string Temail {get; set;}//Enter the mailbox again [DisplayName ("id")] [RegularExpression (@ "\d{17}[\d|x]        |\D{15} ", errormessage =" Identity card number format error ")] public string Identityno {get; set;}//Social Security Number//<summary> Range: Used to specify the minimum and maximum values for a numeric type value. The "minimum" value of the first number in parentheses is the "maximum"///</summary> [DisplayName ("Age")] [Required (Allowemptystrings=false,        Errormessage= "Age cannot be empty")] [Range (10,150,errormessage= age cannot be greater than {2}, and cannot be less than {1} ")] public int ages {get; set;}//Age <summary>///DisplayFormat: Various formatting options for handling properties. When a property contains a null value, you can provide optional display text, or a generic containingDisable HTML encoding, and you can specify a format string for the runtime to apply to the property value. </summary> [DisplayName ("Amount")] [DataType (datatype.currency)]//currency: Represents currency value [Displayforma T (applyformatineditmode=true,dataformatstring= "{0:c}")] [Required (errormessage = "Amount cannot be empty")] [Range (typeof (DE Cimal), "20.0", "30.0", errormessage = "Amount between {1} and {2}")] public decimal Money {get; set;}//Amount [Display (Nam E= "mobile number")]//[datatype (Datatype.phonenumber)] [RegularExpression (@ "((\d{11}) |^ ((\d{7,8}) | ( \D{4}|\D{3})-(\d{7,8}) | (\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}) |        (\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})) ", errormessage =" malformed ")] public int Phome {get; set;} [Display (name= "Birthday")]//[displayformat (applyformatineditmode=true,dataformatstring= "YYYY/MM/DD")] [Required] The value of the current field cannot be null public DateTime Birthday {get; set}//Birthday [Display (name= "Remarks")] [DataType (Datatype.mult Ilinetext)]//The current field is a multiline text public string RemarKS {get; set;}//Remarks}} 

View (Index)

@model mvcapplication2.models.userinfo@{Layout = null;} <! DOCTYPE html>


MVC Data validation

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.