Model validation in ASP. NET MVC5

Source: Internet
Author: User

Model validation is an important part of ASP. This article describes several ways to model validation in ASP. NET MVC.

    • Dataannotation
    • Validationattribute
    • Ivalidatableobject
    • IDataErrorInfo
dataannotation

Dataannotation translation is the meaning of "data annotations", the Dataannotation namespace contains some features for validating the model, such as: Requiredattribute,compareattribute, DisplayAttribute and so on, when we create the model, we can validate the data by labeling the corresponding attribute to the field.

Create Model:

 Public classperson{[Display (Name="name")] [Required (ErrorMessage="the name is required! ")]     Public stringName {Set;Get; } [Display (Name="name")]     Public intAge {Set;Get; }}

The code in view:

@model ebuy.website.models.person@{Layout = null;}<!DOCTYPE HTML><HTML><Head>    <Metaname= "Viewport"content= "Width=device-width" />    <title>Index</title></Head><Body>    <Div>        <H3style= "color:red;">@Html. ValidationSummary ()</H3>    </Div>    <Div>@using (Html.BeginForm ("Evaluate", "home", "Post") {@Html. labelfor (Model = model.name) @Html. textboxfor (model = model.name) @Html. Labelfor (model = model.age) @Html. Tex Tboxfor (Model = model.age)<inputtype= "Submit"value= "Submit" />        }    </Div></Body></HTML>

The code in the controller:

 Public classhomecontroller:controller{ PublicActionResult Index () {returnView (); }     Publicactionresult Evaluate (person person) {if(modelstate.isvalid) {returnContent ("Evaluate success!"); }        returnView ("Index", person); }}

To run the program:

Note that RequiredAttribute is not marked on the age property, but still indicates that the age field must be because age is of type int, int type cannot be null, and ASP. NET MVC is required for nullable types .

Valuationattribute

In addition to using some of the predefined features in dataannotation for data validation, we can also customize some validation features. Here we implement custom validation by covering the IsValid method of the Valudationattribute class in the Dataannotation namespace. The sample code is as follows:

 Public classcheckageattribute:validationattribute{Private int_minage;  PublicCheckageattribute (intminage) {_minage=Minage; }     Public Override BOOLIsValid (Objectvalue) {        if(Value is int)        {            varAge = value as int?; if(age = =NULL)            {                return false; }            if(Age <_minage) {                return false; }            return true; }        return false; }     Public Override stringFormaterrormessage (stringname) {        return Base.    Formaterrormessage (name); }}

Labeling Features:

 Public classperson{[Display (Name="name")] [Required (ErrorMessage="the name is required! ")] [MaxLength (4, errormessage ="it's too long.")]     Public stringName {Set;Get; } [Display (Name="Age")] [Checkage ( -, errormessage ="Too young! ")]     Public intAge {Set;Get; }}

Then run the program:


Ivalidatableobject

By implementing the Ivalidatableobject interface for data validation, the sample code is as follows:

 Public classperson:ivalidatableobject{[Display (Name="name")]     Public stringName {Set;Get; } [Display (Name="Age")]     Public intAge {Set;Get; }  PublicIenumerable<validationresult>Validate (Validationcontext validationcontext) { person person= Validationcontext.objectinstance asPerson ; if(Person = =NULL)        {            yield  Break; }        if(string. IsNullOrEmpty (person. Name)) {yield return NewValidationresult ("What's your surname? "); }        if(person. Age < -)        {            yield return NewValidationresult ("It's too young! "); }    }}

To run the program:


IDataErrorInfo

The implementation of the IDataErrorInfo interface can also be used for data validation, the sample code is as follows:

 Public classperson:idataerrorinfo{[Display (Name="name")]     Public stringName {Set;Get; } [Display (Name="Age")]     Public intAge {Set;Get; }  Public string  This[stringColumnName] {        Get        {            Switch(columnName) { Case "Name":                    if(string. IsNullOrEmpty (Name)) {return "Yanguoliusheng, a man who has a"; }                    return NULL;  Case " Age":                    if(Age < -)                    {                        return "It's still a light age! "; }                     Break; }            return NULL; }    }     Public stringError {Get        {            return "Something went wrong! "; }    }}

To run the program:

Copyright notice

This article is the author original, the copyright belongs to the author Snow Feihong all. Reproduced must retain the integrity of the article, and in the page marked the location of the original link.

If you have questions, please email and contact the author.

Model validation in ASP. NET MVC5

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.