04 – MVC Model
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
// Dispaly Attribute is consumed by @Html.LableFor()
[Display(Name = "Confirm password")]
//Cross-Property comparison, new in MVC3
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
|
The result:
-
Custom Validation Attributes
Create my own Validation Class:
public class GreaterThanDateAttribute : ValidationAttribute // Needs to import [System.ComponentModel.DataAnnotations;]
{
public GreaterThanDateAttribute(string otherPropertyName)
:base("{0} must be greater than {1}") // This defines the ErrorMessage String
{
OtherPropertyName = otherPropertyName;
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessage, name, OtherPropertyName); // "{0} must be greater than {1}"
}
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)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
return null;
}
public string OtherPropertyName { get; set; }
}
|
In the Model TimeCard.cs, apply GreaterThanDate attribute to EndDate property
Test with invalid data:
Assign an action to perform the validation by applying [Remote] attribute to the property that needs to be validated
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
// 1.Action name; 2.Controller name; 3. Error message
[Remote("ValidateUser","Account",ErrorMessage="Username is invalid")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
|
In Controller, add an action “ValidateUser”, validate the user name against database
public JsonResult ValidateUser(string username)
{
//Validate user name against database
var result = _db.ValidateUserName(username);
return Json(result, JsonRequestBehavior.AllowGet);
}
|
Validating in View: