Your SlideShare is downloading. ×
Validations in MVC<br />Eyal Vardi<br />CEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com<br />
Agenda<br />Data Annotations Validation <br />Self Validation Models<br />Custom Validation<br />Entity Level Validation<b...
Validation Scenario (WWWH)<br />When to validate?<br />During data input<br />On submitting data<br />After submission<br ...
Model Data Annotations<br />Specify validation for individual fields in the data model.<br />System.ComponentModel.DataAnn...
Metadata Classes<br />The MetadataTypeAttributeattribute enables you to associate a class with a data-model partial class....
Server Validation<br />public ActionResult Edit( Contact contact ){    if (ModelState.IsValid)     {         // The model ...
Server Validation<br />[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit( int id, FormCollection collection ){   Produ...
Validation Attributes<br />Metadata Validation Attributes:<br />[Required]<br />[Exclude]<br />[DataType]<br />[Range]<br ...
Self Validation Models<br />Validation Order:<br />Property attributes<br />Class attributes<br />Validate interface<br />...
Self Validation Models<br />public class UserModel : IValidatableObject{   public int Age { get; set; }   public IEnumerab...
CustomValidation Attribute<br />The custom class must:<br />Public, static method<br />At lest 1 parameter<br />Returns Va...
CustomValidation Attribute<br />[MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]<br />publicpartialclassEmpl...
Custom Validation Attribute<br />Derived from ValidationAttributein order to have library of custom validation attributes....
Client-Side Validation<br />
Client-Side Validation<br /><script src="@Url.Content("~/jquery1.4.4.min.js")"  type="text/javascript" /><script src="@Url...
public class Contact{   [StringLength(4)]   public string Name { get; set; }}<br />Model<br /><div class="editor-field">  ...
IClientValidatable<br />Enables MVC to discover at run time whether a validator has support for client validation.<br />pu...
public class ModelClientValidationRangeDateRule : ModelClientValidationRule<br />{         <br /> public ModelClientValida...
JQuery Date Range Validation<br />(function ($) {<br />   $.validator.addMethod('rangeDate', function (value, element, par...
JQuery Date Range Validation<br />$(document).ready( function () <br />{     <br />  function getDateYymmdd(value)<br />  ...
IClientValidatable<br />
Remote Validator<br />Remote Validator<br />JQuery<br />publicclassContact<br />{<br />   [Remote("UserNameAvailable", "My...
Remote Validator<br />
Summary<br />New validation features<br />Data annotations & ValidationContext<br />Self validation, IValidatebleObject<br...
Upcoming SlideShare
Loading in...5
×

ASP.NET MVC 3.0 Validation

6,343

Published on

ASP.NET MVC shipped both client- and server-side validation support.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
6,343
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • Server Side: - Domain Services: Attribute, ODATA, - Domain Services with ModelClient Side: - Domain Context - Domain Data Source - NavigationSecurity:
  • [ExternalReference] [Association(&quot;Sales_Customer&quot;, &quot;CustomerID&quot;, &quot;CustomerID&quot;)]
  • [ExternalReference] [Association(&quot;Sales_Customer&quot;, &quot;CustomerID&quot;, &quot;CustomerID&quot;)]
  • Transcript of "ASP.NET MVC 3.0 Validation"

    1. 1. Validations in MVC<br />Eyal Vardi<br />CEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com<br />
    2. 2. Agenda<br />Data Annotations Validation <br />Self Validation Models<br />Custom Validation<br />Entity Level Validation<br />Client-Side Validation<br />Remote Validation<br />
    3. 3. Validation Scenario (WWWH)<br />When to validate?<br />During data input<br />On submitting data<br />After submission<br />What to validate?<br />Property<br />Entity<br />Domain Operation<br />Where to validate?<br />Server Only<br />Client + Server<br />How do we write logic?<br />Attributes<br />Add code in operation<br />Custom validation class<br />
    4. 4. Model Data Annotations<br />Specify validation for individual fields in the data model.<br />System.ComponentModel.DataAnnotations<br />Provide both client and server validation checks with no additional coding required by you. <br />public class ProductMD{    [StringLength(50), Required]    public object Name { get; set; }                            [Range(0, 9999)]    public object Weight { get; set; }}<br />
    5. 5. Metadata Classes<br />The MetadataTypeAttributeattribute enables you to associate a class with a data-model partial class.<br />[MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]<br />publicpartialclassEmployee<br />}<br />internalsealedclassEmployeeMetadata<br /> }<br /> [StringLength(60)]<br /> [RoundtripOriginal]<br />public string AddressLine { get; set; }<br /> }<br />}<br />
    6. 6. Server Validation<br />public ActionResult Edit( Contact contact ){    if (ModelState.IsValid)     {         // The model Valid.    }    else    {        ModelState.AddModelError( "*", "contract not valid" );    }    return View(contact);<br />}<br />Validate Model<br />
    7. 7. Server Validation<br />[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit( int id, FormCollection collection ){   Product prd = GetProduct(id);   if ( ! TryUpdateModel( prd ) )   {      return View(prd);   }               // Persist changes back to database   _db.SaveChanges();   // Perform HTTP redirect to details page for the saved Dinner   return RedirectToAction("Details", new { id = prd.ProductID });}<br />Validate Product<br />
    8. 8. Validation Attributes<br />Metadata Validation Attributes:<br />[Required]<br />[Exclude]<br />[DataType]<br />[Range]<br />[StringLength(60)]<br />[RegularExpression]<br />[AllowHtml]<br />[Compare]<br />[MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]<br />publicpartialclassEmployee<br />}<br />internalsealedclassEmployeeMetadata<br /> }<br /> [StringLength(60)]<br /> [RoundtripOriginal]<br />public string AddressLine { get; set; }<br /> }<br />}<br />
    9. 9. Self Validation Models<br />Validation Order:<br />Property attributes<br />Class attributes<br />Validate interface<br />If you have any DataAnnotations attributes on your properties that fail then your Validate implementation will not be called.<br />
    10. 10. Self Validation Models<br />public class UserModel : IValidatableObject{   public int Age { get; set; }   public IEnumerable<ValidationResult> Validate( ValidationContext vc )   {       if( Age < 18 )       {            yield return                new ValidationResult(                      "User age should be higher then 18",                       new string[] { "Age" });       }   }}<br />
    11. 11. CustomValidation Attribute<br />The custom class must:<br />Public, static method<br />At lest 1 parameter<br />Returns ValidationResult<br />public class MyValidator<br />{<br /> public static ValidationResultValidationAddress(short value,ValidationContextcontext) <br />{<br />ValidationResultresult = <br /> ( value >= 0.0 && value <= 100.0 ) ? <br />ValidationResult.Success:<br /> new ValidationResult("Is out of range");<br /> return result; <br /> } <br /> } <br />
    12. 12. CustomValidation Attribute<br />[MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]<br />publicpartialclassEmployee<br />}<br />internalsealedclassEmployeeMetadata<br /> }<br /> [CustomValidation( typeof(MyValidator) , "ValidationAddress")]<br />public short AddressNum { get; set; }<br /> }<br />}<br />
    13. 13. Custom Validation Attribute<br />Derived from ValidationAttributein order to have library of custom validation attributes.<br />public class EvenNumberAttribute : ValidationAttribute{   protected override ValidationResult IsValid( object  value ,           ValidationContext  validationContext )   {       return          ( (short) value % 2 == 0 ? ValidationResult.Success : new ValidationResult("...") );   }<br />}<br />
    14. 14. Client-Side Validation<br />
    15. 15. Client-Side Validation<br /><script src="@Url.Content("~/jquery1.4.4.min.js")"  type="text/javascript" /><script src="@Url.Content("~/jquery.validate.min.js")" type="text/javascript"/><br /><script src="@Url.Content("~/jquery.validate.unobtrusive.min.js")" ... /><br />@HtmlHelper.EnableClientValidation = true; // By default define in config file.<br />@using (Html.BeginForm()) <br />{    @Html.ValidationSummary(true)    <fieldset>        <legend>TimeCard</legend>        <div class="editor-label">            @Html.LabelFor(model => model.Username)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Username)            @Html.ValidationMessageFor(model => model.Username)        </div><br /> </fieldset><br />}<br />
    16. 16. public class Contact{   [StringLength(4)]   public string Name { get; set; }}<br />Model<br /><div class="editor-field">    @Html.TextBoxFor(m => m.Name)    @Html.ValidationMessageFor(m => m.Name)</div><br />View<br /><div class="editor-field">  <input name="Name" id="Name"type="text" value=""         data-val="true | false"          data-val-length="Error Message"          data-val-length-max="4"    />  <span class="field-validation-valid"          data-valmsg-for="Name"          data-valmsg-replace="true | false" /></div><br /><div class="editor-field">  <input name="Name" id="Name"type="text" value=""         <br />         <br />             />  <span class="field-validation-valid"          <br />  /></div><br /><div class="editor-field">  <input name="Name" id="Name"type="text" value=""         data-val="true | false"          data-val-length="Error Message"          data-val-length-max="4"    />  <span class="field-validation-valid"          <br />  /></div><br />HTML<br />Client Attribute<br />
    17. 17. IClientValidatable<br />Enables MVC to discover at run time whether a validator has support for client validation.<br />public sealed class DateRangeAttribute : ValidationAttributeIClientValidatable{    public IEnumerable<ModelClientValidationRule>             GetClientValidationRules( ModelMetadata metadata, ControllerContext context)   {       return new[]{ <br /> new ModelClientValidationRangeDateRule(<br />                    FormatErrorMessage( metadata.GetDisplayName() ),                         _minDate,<br />                  _maxDate) };   }<br />}<br />
    18. 18. public class ModelClientValidationRangeDateRule : ModelClientValidationRule<br />{         <br /> public ModelClientValidationRangeDateRule(<br /> string errorMessage, DateTime minValue, DateTime maxValue)<br /> {             <br />ErrorMessage  = errorMessage;<br />ValidationType  = "rangedate";<br />ValidationParameters["min"] = minValue.ToString("yyyy/MM/dd"); <br />ValidationParameters["max"] = maxValue.ToString("yyyy/MM/dd");<br /> }     <br />}<br /><input id="Foo_Date"class="date" name="Foo.Date" type="text" value="…"<br /> data-val="true"<br /> data-val-rangedate="Error Message"    <br /> data-val-rangedate-max="2010/12/20"     <br /> data-val-rangedate-min="2010/12/02"     <br /> data-val-required="The Date field is required." />   <br />  <span class="field-validation-valid"        <br />    data-valmsg-for="Foo.Date"           <br /> data-valmsg-replace="true" /><br />
    19. 19. JQuery Date Range Validation<br />(function ($) {<br /> $.validator.addMethod('rangeDate', function (value, element, param){<br />if(!value) returntrue; <br />try{ vardateValue = $.datepicker.parseDate("dd/mm/yy", value); }<br />catch(e) { return false; }<br />returnparam.min <= dateValue && dateValue <= param.max;<br /> });<br /> // The adapter to support ASP.NET MVC unobtrusive validation<br /> $.validator.unobtrusive.adapters.add('rangedate', ['min', 'max'], function(options) {<br />varparams = {<br /> min: $.datepicker.parseDate("yy/mm/dd", options.params.min),<br /> max: $.datepicker.parseDate("yy/mm/dd", options.params.max)<br /> };<br />options.rules['rangeDate'] = params;<br />if (options.message) {<br />options.messages['rangeDate'] = options.message;<br /> }<br /> });<br />} (jQuery));<br />
    20. 20. JQuery Date Range Validation<br />$(document).ready( function () <br />{     <br /> function getDateYymmdd(value)<br />  {        <br /> if (value == null)<br />            return null;<br />     return $.datepicker.parseDate("yy/mm/dd", value); <br />    }<br />   <br />  $('.date').each( function ()<br />  {<br />        var minDate = getDateYymmdd( $(this).data("val-rangedate-min"));<br />        var maxDate = getDateYymmdd( $(this).data("val-rangedate-max"));<br /> $(this).datepicker(<br /> {             <br />dateFormat: "dd/mm/yy", <br />              minDate : minDate,<br />            maxDate : maxDate<br />         });    <br />  });<br />});<br />
    21. 21. IClientValidatable<br />
    22. 22. Remote Validator<br />Remote Validator<br />JQuery<br />publicclassContact<br />{<br /> [Remote("UserNameAvailable", "My")]<br />publicstringUserName { get; set; }<br />}<br />Model<br />public JsonResult UserNameAvailable(string username)<br /> {    if (MyRepository.UserNameExists(username))    ...                  return Json( “message” , JsonRequestBehavior.AllowGet);}<br />MyController<br /><input ...           data-val-remote="UserName is invalid."    data-val-remote-additionalfields="*.UserName"    data-val-remote-url="/Validation/IsUID_Available"  /><br />
    23. 23. Remote Validator<br />
    24. 24. Summary<br />New validation features<br />Data annotations & ValidationContext<br />Self validation, IValidatebleObject<br />Client validation<br />Remote validation<br />Unobtrusive client validation<br />

    ×