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; } } }
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; } }
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("...") ); } }
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 }); }); });