1

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

1 Answer 1

2

How do you know the validation doesn't fire? Are you setting a break point in your controller?

You are not displaying any validation errors in your view. You need to add the following lines to the view.

@Html.ValidationMessageFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.LastName)

You will want to remove the custom validation from the class. Leave it on the properties though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.