Tuesday, July 10, 2012

Data Validation using Data Annotations

Data Annotations

[Required()]
[StringLength(25)]

[Range(1,120)]
public int Hours{get; set;}

[Compare("Hours")]
public int ConfirmHours{get; set;}

<div class="editor-label">
@Html.LabelFor(model=>model.ConfirmHours, "Please confirm the hours worked")
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.ConfirmHours)
@Html.ValidationMessageFor(model=>model)
</div>

Custom Validation Attributes

public class GreaterThanDateAttribute : ValidationAttribute
:base("{0} must be greater than {1}")
{
public string OtherPropertyName{get; set;}

public GreaterThanDateAttribute(string otherPropertyName)
{
OtherPropertyName = otherPropertyName;
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessageString, name, otherPropertyName);
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(otherPropertyName);
var otherDate = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisDate = (DateTime)value;
if(thisDate <= otherDate)               //failed
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}

return null;                                      //succeeded
}
}

public DateTime StartDate{get; set;}

[GreaterThanDate("StartDate")]
public DateTime EndDate{get; set;}


No comments: