Reputation: 313
I have a Model:
[Required(ErrorMessage = "Dit veld is verplicht")]
[Range(60, 60000, ErrorMessage = "De waarde moet tussen de 60 en 60000 liggen")]
public double? Kilometers { get; set; }
[Required(ErrorMessage = "Dit veld is verplicht")]
public int? Minutes { get; set; }
And my html:
<div class="control-group container-trigger" id="container-distance">
<label class="control-label" for="trigger-distance">Aantal kilometers</label>
<div id="distance" class="controls">
@Html.TextBoxFor(m => m.Alert.Kilometers, new { id = "trigger-distance", @name = "trigger-distance" })
@Html.ValidationMessageFor(m => m.Alert.Kilometers, "", new { @class = "error-0" })
</div>
</div>
<div class="control-group container-trigger" id="container-minutes">
<label class="control-label" for="trigger-minutes">Aantal minuten</label>
<div id="minutes" class="controls">
@Html.TextBoxFor(m => m.Alert.Minutes, new { id = "trigger-minutes", @name = "trigger-minutes" })
@Html.ValidationMessageFor(m => m.Alert.Minutes, "", new { @class = "error-0" })
</div>
</div>
I have a dropdownlist and if I make a selection I need it to show a textbox. If I select the first option, it will show a textbox for minutes. If I select the second option then it will show a textbox for distance. What I have is if I click on the submit button I get a validation error for the textbox that isn't displayed from the form, but they must be only required if they are shown!
What can I do to fix this?
Upvotes: 0
Views: 499
Reputation: 670
Conditional Validation will help you achieve what you're looking for http://foolproof.codeplex.com/
Upvotes: 1
Reputation: 1518
I assume you're using jquery for unobtrusive validation? If so, you can use the $.validator.defaults.ignore property to specify any selectors that should be ignored during validation, for example:
$.validator.defaults.ignore = ':disabled,:hidden,.ignore';
Just make sure that you spacify something that matches your hidden controls here.
Upvotes: 0
Reputation: 1056
you have made them both required using the [required] attribute. therefore if you dont set a value for any of them it will throw a client side validation. you have to either remove the "required" attribute or remove the "ValidationMessageFor" from html
Upvotes: 0