Reputation: 446
I got a class that inherits IValidatableObject
which my validations are validated through IEnumerable<ValidationResult>
function. Inside this function I manage to check all the fields and return one ValidationResult
message.
However, My problem is the membernames.ToArray()
is only passing one value. I prove it during debegging the View page and when it checks the field if it is valid using Html.ViewData.ModelState.IsValid("<fieldname>")
Below is the code when I return the ValidationResult message with all the fields that are not valid. The string.Join(",", membernames.ToArray())
will return a collection of the fields. (i.e "FirstName", "LastName")
List<string> membernames = new List<string>();
//Firstname
if (FirstName.Trim() == string.Empty)
{
isValid = false;
membernames.Add(@"""FirstName""");
}
//Lastname
if (LastName.Trim() == string.Empty)
{
membernames.Add(@"""LastName""");
isValid = false;
}
if (!isValid)
{
yield return new ValidationResult("Please complete all fields marked with *", new[] { string.Join(",", membernames.ToArray()) });
}
Do I pass the correct type in the new[] { .. }
?
Please advise. Thanks in advance.
Upvotes: 0
Views: 1261
Reputation: 2428
In Mvc3 :
in Controller:
ModelState.AddModelError("FirstName", "FirstName Minimum 2 Char");
ModelState.AddModelError("FirstName", "FirstName Maximum 20 Char");
ModelState.AddModelError("LastName", "Error Message");
if You Want only one Error Message for All property:
ModelState.AddModelError("", "First Error Message");
ModelState.AddModelError("", "Second Error Message");
in View:
@using (Html.BeginForm()) {
@Html.ValidationSummary()
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
//other fields...
}
don't forget jquery and Validation plugin:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Upvotes: 0