0

I've created person model with custom validation to insure the user enters a name for the person. The problem is the name is made up of several fields and i only require at least one of the fields be completed.

Here is my validation code:

if (string.IsNullOrWhiteSpace(this.Title) && 
    string.IsNullOrWhiteSpace(this.Initals) &&
    string.IsNullOrWhiteSpace(this.Forename) && 
    string.IsNullOrWhiteSpace(this.Surname) && 
    string.IsNullOrWhiteSpace(this.Company))
    yield return new ValidationResult("You must enter a name or company name.", 
        new string[] { "Title", "Initals", "Forename", "Surname", "Company" });

I expected to see a single error message and 5 fields highlighted, however i get 5 error messages and five fields highlighted. I'm only displaying error messages using @Html.ValidationSummary().

How do I suppress the 4 extra messages and still highlight the 5 fields that are the problem.

1 Answer 1

3

Some of quick solutions:

1) Set 2 ValidationResult in validation code:

...
yield return new ValidationResult("You must enter a name or company name.");
yield return new ValidationResult("any text",
    new string[] { "Title", "Initals", "Forename", "Surname", "Company" });

2) Exclude property validation message from summary, in your View:

@model SomeModel
...
@Html.ValidationSummary(true)
...

So you'll get single message and highlighted inputs.

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.