Reputation: 691
I'm able to validate each textbox separately by using data-val true but how can I do multi-field validation? I want to validate first name and last name together. Both fields are required. I'm using guid to generate an unique id so the values can be passed to the controller.
<input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].FirstName" />
<span data-valmsg-for="FormResponse.NameResponse[@guid].FirstName" data-valmsg-replace="true"></span>
<input type="text" data-val="true" data-val-required="This field is required." name="FormResponse.NameResponse[@guid].LastName" />
<span data-valmsg-for="FormResponse.NameResponse[@guid].LastName" data-valmsg-replace="true"></span>
Upvotes: 1
Views: 264
Reputation: 9463
To validate on the server side (at the time when the request is bound to the ViewModel), implement IValidatableObject
:
using System.ComponentModel.DataAnnotations;
public class MyViewModel : IValidatableObject {
// note that we do not have a [Required] attribute here,
// or we would show two validation messages if one property is not set
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (string.IsNullOrWhiteSpace(FirstName) ||
string.IsNullOrWhiteSpace(LastName)) {
yield return new ValidationResult(
"Both first and last name are required!",
new[] { "FirstName", "LastName" }
);
}
}
}
The messages generated by this validation method can be rendered using @Html.ValidationSummary()
. It will be shown after a round trip to the server on which validation failed.
You can test whether the model is valid in the controller by calling ModelState.IsValid
.
ASP.NET MVC: Self Validating Model objects
Upvotes: 1