23rd Chapter Model Validation

Source: Internet
Author: User

----------------------------------------------

Note: 1. In Web. config, add <globalization culture= "en-us" uiculture= to the system.web element to change the zone file settings in the >.

2.datatype annotation Properties cannot be used to validate user input, only render hints using the template helper.

  3. Implementing the Ivalidatableobject Interface validation model class, which does not support client-side validation

----------------------------------------------

model Validation: Ensures that the data the user receives is appropriate for binding to the model, and when inappropriate, gives the user feedback to help with the process of modifying the problem.

Process:

1. check the received data and maintain the integrity of the domain model in one of the ways. Prevent strange situations in your application by denying data that is meaningless in a domain environment.

2. help users fix problems and provide users with the information and tools they need to follow and interact with the application.

First, explicitly validate the model:

  1. Set the check box style:

In the ~/views/shared/editortemplates/boolean.cshtml:

@model bool @if (ViewData.ModelMetadata.IsNullableValueType) {@Html. dropdownlistfor (M = m, new SelectList (new [] {"Not Set", "True", "False"}, Model))}else{modelstate state = Viewdata.modelstate[viewdata.modelmetadata.propertyna    Me]; BOOL value = Model??    False if (state! = null && state. Errors.Count > 0) {<Divclass= "Input-validation-error"style= "Float:left">@Html. CheckBox ("", value)</Div>} else {@Html. CheckBox ("", Value)}}

2. Display the verification message:

@model modelvalidation.models.appointment@{viewbag.title = "Make A Booking";}<H2>Appointment</H2>@using (Html.BeginForm ()) { @Html. ValidationSummary () <P>Name: @Html. editorfor (M = m.clientname)</P>        <P>Appointment Date: @Html. editorfor (M = m.date)</P>    <P>@Html. Editorfor (M + m.termaccepted) receive agreement terms</P>      <inputtype= "Submit"value= "Appointment"/>}

Useful ValidationSummary Helper Overloading method

Overloaded methods Describe
Html.validationsummary () Generate a summary of all validation errors
Html.validationsummary (BOOL) True: only model-level errors are displayed. Default false: Show All errors
Html.validationsummary (String) Add a message (string) before all validation error summaries
Html.validationsummary (bool,string) Add a message (string) True before all validation error summaries: Show only model-level errors

To display an attribute-level validation message:

@model modelvalidation.models.appointment@{viewbag.title = "Make A Booking";}<H2>Appointment</H2>@using (Html.BeginForm ()) {@Html. ValidationSummary (True)<P>Name: @Html. editorfor (M = m.clientname) @Html. Validationmessagefor (M=>m.clientname)</P>        <P>Appointment Date: @Html. editorfor (M = m.date) @Html. Validationmessagefor (M=>m.date)</P>    <Div>@Html. Editorfor (M + m.termaccepted) receive agreement terms @Html. Validationmessagefor (m=>m.termaccepted)</Div>      <inputtype= "Submit"value= "Appointment"/>}

second, validation is performed in the default model binder

Ways to add validation to the binding process in Defaultmodelbinder

Method Describe Default implementation
onmodelupdated Called when the binder attempts to assign values to all the properties in a model object Use the validation rules defined by the model metadata and register the errors with Modelstate.
SetProperty Called when the binder applies a value to a particular property

If the property cannot hold a null value, and no value is available,

A "The <name> Fieldis required" error message will be registered with Modelstate;

If there is a value but cannot be parsed, it will register "the value <value> is not validfor <name>"

1. Specify validation rules with metadata:

     Public classAppointment//: Ivalidatableobject{[DisplayName ("Customer Name")] [Required] Public stringClientName {Get;Set; }        [DataType (Datatype.date)] [DisplayName ("Date")] [Required (ErrorMessage="Please enter a time")]         PublicDateTime Date {Get;Set; } [DisplayName ("Terms of acceptance")] [Range (typeof(BOOL),"true","true", errormessage ="must accept the terms of the agreement")]           Public BOOLtermaccepted {Get;Set; }

Built-in validation annotation properties

td> maximum length of a string value, Minimum length: [Stringlength (10,minimumlength=2)]
annotation Properties /strong> example Description
Compare [Compare ("Myotherproperty)] Two properties must have the same value. This is useful when the user is asked to provide two identical values for a property.
range [Range (10,20)] A numeric value (implementing IComparable's property type), value range, [range (int. minvalue,50)]
regularexpression [RegularExpression ("pattern")] A string value that must be The regular expression pattern that must match. All values, not substrings. Case insensitive: [RegularExpression ("(? i) Mypattern")]
Required [Required] non-null value. Spaces can be accepted: [Required (Allowemptystrings=true)]
stringlength [Stringlength (+)]

Third, client authentication

Enable: <AppSettings> in 1.web.config

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

2. Refer to three JS libraries:

     Jquery

Jquery. Validate

Jquery.validate.unobtrusive

Remote Authentication: You must josnresult a type, receive a string parameter, perform a type conversion, parse, or explicit model binding.

1. Action method: 

         PublicJsonresult Validatedate (stringdate)            {DateTime parsedate; if(! Datetime.tryparse (Date, outparsedate)) {                returnJson ("Please enter a date formatted as "MM/DD/YYYY"", Jsonrequestbehavior.allowget); }            Else if(datetime.now>parsedate) {                returnJson ("Please enter a future time to make an appointment", Jsonrequestbehavior.allowget); }            Else            {                returnJson (true, Jsonrequestbehavior.allowget); }        }

2.Remote Annotation Properties:

        [Remote ("validatedate","Home")]           Public Get set; }

Source: Http://yunpan.cn/ccGAZD7d5QL6Z Access Password 672a

23rd Chapter Model 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.