Scenario: The user should fill out a 开发者_JS百科form and based on his choices different properties are displayed(using jquery .show and .hide). Problem: I want some of those properties that are shown to be required(but only when they are shown ofc). The [Required] attribute doesn't care if the property is shown or not. So if I use [Required] the user are asked to fill out properties he can't see. Solution: ?
You could use the RequiredIf attribute to perform conditional validation:
[RequiredIf("HiddenFoo", "true", ErrorMessage = "Foo is required")]
public string Foo { get; set; }
public string HiddenFoo { get; set; }
Now, add a hidden field called HiddenFoo
and then toggle its value when you are showing/hiding the Foo
textbox. Foo
will be required only if HiddenFoo="true"
.
精彩评论