Data validation in MVC

Source: Internet
Author: User
Tags validation examples

Http://www.studyofnet.com/news/339.html

Http://www.cnblogs.com/kissdodog/archive/2013/05/04/3060278.html

This article is guided by: the model in ASP. MVC3 is self-validating, which is passed. The NET4 System.ComponentModel.DataAnnotations namespace is completed. All we have to do is add the corresponding validation tag (Attributes) to each property of the model class and let the MVC3 framework do the validation for us. The following describes the knowledge of data validation in MVC

One, client authentication

Client-side validation is primarily intended to improve the user experience and to complete validation without the Web page being brushed back.

1. The first step is to enable client-side validation in Web. config, which is already available in MVC3 's own template project :

<add key= "clientvalidationenabled" value= "true"/>

<add key= "unobtrusivejavascriptenabled" value= "true"/>

2, and then on the Verified view page to add such two JavaScript, note that they are dependent on 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>

3, there are two kinds of authentication message display, one is ValidationSummary, it can display a summary of the verification message, including the message 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 the model that corresponds to the HTML control :

@Html. validationmessagefor (M = m.username) second, the model is added to verify the tag 1. Basic Features


(1), Required

Required option, a validation error is raised when the submitted form is missing this value.



(2), stringlength

Specify the allowed length

Specify the maximum length:

[Stringlength (20)]//maximum length of 20 characters


Specify the shortest limit to the maximum:

[Stringlength (20,MINIMUMLENGTH=3)]//Maximum length is not more than 20 characters, the minimum can not be less than 3 characters

(3), regularexpression

The regular expression can match the string, if it does not match, then report a validation error

[RegularExpression (@ "[A-za-z0-9.%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4} ")]


  

(4), Range

The range attribute is used to specify the minimum and maximum values for numeric type values.

[Range (35,44)]//Integer, Min. 35, max 44
[Range (typeof (Decimal), "0.00", "49.99")]//decimal type


 

(5), Remote

Allows client-side validation logic to be performed using the server's callback function. To be blunt is to support Ajax validation.

This is a demo that writes the existence of an asynchronous authentication user name:

C # codeCopy
        [Required]
        [Remote ("Checkusername", "Home")]
        public string UserName
        {            get;            Set;        }

Controller Code :

C # codeCopy
        Public Jsonresult Checkusername (string UserName)
        {            bool result = true;            if (UserName = = "Admin")            {                result = false;            }            Return Json (Result,jsonrequestbehavior.allowget);        }

Show Results :

(6), Compare



Used to ensure that two objects of a template object have the same value.

For example, it is time for the Compare property to be required to confirm the password again after the password is usually entered.

[Compare ("Property name to compare]")


2. Custom error message



Each attribute allows the passing of a parameter with a custom error prompt message.

C # codeCopy
        [Required (errormessage= "username must be filled in")]
        [Remote ("Checkusername", "Home", errormessage= "This user name already exists")]
        public string UserName
        {            get;            Set;        }

Custom error messages, there is also a format item, such as

C # codeCopy
[Required (errormessage= "{0} must be filled in")]
Publit string Name
{  get;  Set;   }

{0} is replaced with the name when it is entered .

If the above verification method is not enough, you can also customize the validation

3. Display and edit annotations



(1), Display

If you are using a direct Editorformodel implementation, the display feature can help you set a friendly show name

For example:

[Display (name= "password")]
public string PassWord {get; set;}

(2), Scaffoldcolumn

Hiding HTML helper methods (such as Editorformodel,displayformodel) displays some properties.

[Scaffoldcolumn (FALSE)]//edit box for this property is not displayed
public string UserName {get; set;}


Although Scaffoldcolumn can not display some properties on the page to be edited, but if the submitted form has this property value, the model binding mechanism will still bind this property value. To remove the explicit [Bind], this is not related to this article. Not mentioned here.


(3), DisplayFormat

The DisplayFormat attribute can be used to handle various formatting options for a property. When a property contains a null value, you can provide optional display text, or you can turn off HTML encoding for the property that contains the tag, and you can specify a format string for the runtime to apply to the property value.

For example:

[DisplayFormat (Applyformatineditmode = true, DataFormatString = "{0:c}")]
Public decimal Money {get; set;}


Thus, when there is an initial value, the code shown will look like this:

Note that is the initial value, if it is directly filled out, there will be no sign. Look at the initial values set in the controller:

C # codeCopy
        Public ActionResult Personadd ()
        {            Person_model p = new Person_model ();            P.money = 12.10M;            Return View (P);        }

This display style is not useful for submitting back to the controller, because the model binder will not be able to resolve the returned price value. How to use your own discretion, to show or OK.



(4), ReadOnly

If you ensure that the default model binder does not update the properties with the new values in the request, you can add the ReadOnly attribute to the attribute:

[ReadOnly (True)]
public string Name {get; set;}


Note that this property still displays an editable text box to display name, but the model binder does not receive its value, so only the model binder considers the ReadOnly property.


(5), DataType

The datatype attribute can provide the runtime with information about the specific purpose of the property.

For example:

[DataType (Datatype.password)]
public string PassWord {get; set;}

This property can be used to specify multi-select buttons, radio buttons, password entry boxes, and so on for the type of data.

  

(6), UIHint

The UIHint feature provides a template name to the ASP. NET MVC runtime, in case the template helper methods such as (Displayfor and editorfor) render output are used. You can also customize your own template helper methods to override the default behavior of ASP.



(7), Hiddeninput

Hiddentinput in namespace SYSTEM.WEB.MVC, it tells the runtime to render an INPUT element with a type attribute value of "hidden". Plainly is <input type= "hidden" value= "xxx"/>

Iii. Validation Examples

1. Create a new MVC project first. Add the following code, the code is very simple: a Person_model class

C # codeCopy
    public class Person_model
    {        [Required]        {get; set;}        [Required]        {get; set;}        [Required]        {get; set;}    }  

2. Controller Class Code

C # codeCopy
    public class Homecontroller:controller
    {Public        ActionResult personadd ()        {            return View ();        }        [HttpPost]        Public ActionResult Personadd (Person_model Model)        {//A line of code to determine if the validation passed            if (modelstate.isvalid)             {                return Redirect ("/home/personmanager");            }            return View ();        }    }  

3. View Code

C # codeCopy
@model MvcApplication1.Models.Person_Model
@{    viewbag.title = "Index";    Layout = "~/views/shared/_layout. Cshtml ";} <form action= "/home/personadd" method= "POST" > Id:<input type= "text" name= "Id" value= ""/> @ Html.validationmessagefor (Model = model.id)//The reason that the verification written in Person_model is displayed to the front-end prompt, mainly the role of this code <br/> Name: <input Type= "text" name= "name" value= ""/> @Html. Validationmessagefor (Model = model.name) <br/> Age: <input type = "Text" name= "Age" value= ""/> @Html. Validationmessagefor (Model = model.age) <input type= "Submit" value= "OK"/ ></form>

4, the effect of implementation

Data validation in MVC

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.