Your SlideShare is downloading. ×
ASP.NET MVC 3.0 Validation
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

ASP.NET MVC 3.0 Validation

6,232
views

Published on

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

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,232
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
4
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Server Side: - Domain Services: Attribute, ODATA, - Domain Services with ModelClient Side: - Domain Context - Domain Data Source - NavigationSecurity:
  • [ExternalReference] [Association("Sales_Customer", "CustomerID", "CustomerID")]
  • [ExternalReference] [Association("Sales_Customer", "CustomerID", "CustomerID")]
  • Transcript

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