I have two separate VIEWS accessing the same MODEL. When I put the validator data annotations on the model, it works as advertised and prevents the data from being submitted (for both views) if left blank or not within range. However, I have one view that should be able to allow empty or null values to be saved for a property whereas another view needs to require information to be entered or selected before it lets it through. In other words, I’d like to turn off the validator on the property within the MODEL for one view and leave it on for the other view. Here’s the example code:
MODEL:
[Range(1, 999, ErrorMessage = "A submittal is required")]
public int SubmittalId { get; set; }
VIEW #1:
<label>@Model.AuditDoc.SubmittalsLabel.ConfigurableLabelDesc</label> @Html.ValidationMessageFor(x => x.AuditDoc.SubmittalId) @Html.DropDownListFor(x => x.AuditDoc.SubmittalId, new SelectList(Model.AuditDoc.ListOfSubmittals, "Id", "Name"))
VIEW #2:
<label>@Model.AuditDoc.SubmittalsLabel.ConfigurableLabelDesc</label> @Html.DropDownListFor(x => x.AuditDoc.SubmittalId, new SelectList(Model.AuditDoc.ListOfSubmittals, "Id", "Name"))
As you can see, I would like to disable that validator data annotation for View #2 and leave it on for View #1.
This isn’t possible via the default set of data annotations.. however, you have the choice of using 2 separate view models or writing your own validationAttribute.
I wrote this once.. although I loathed using it..
Usage:
You could do the same for Range, RegEx, etc..