I have created a custom validator in my asp.net mvc3 application like this:
{
if (customerToValidate.FirstName == customerToValidate.LastName)
return new ValidationResult("First Name and Last Name can not be same.");
return ValidationResult.Success;
}
public static ValidationResult ValidateFirstName(string firstName, ValidationContext context)
{
if (firstName == "Nadeem")
{
return new ValidationResult("First Name can not be Nadeem", new List<string> { "FirstName" });
}
return ValidationResult.Success;
}
and I have decorated my model like this:
[CustomValidation(typeof(CustomerValidator), "ValidateCustomer")]
public class Customer
{
public int Id { get; set; }
[CustomValidation(typeof(CustomerValidator), "ValidateFirstName")]
public string FirstName { get; set; }
public string LastName { get; set; }
}
my view is like this:
@model CustomvalidatorSample.Models.Customer
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
@using (@Html.BeginForm())
{
@Html.ValidationSummary(false)
<div class="editor-label">
@Html.LabelFor(model => model.FirstName, "First Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName, "Last Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
</div>
<div>
<input type="submit" value="Validate" />
</div>
}
But validation doesn't fire. Please suggest solution.
Thanks