Arnstein
Arnstein

Reputation: 986

how to use required attribute on properties that can be hidden in mvc

Scenario: The user should fill out a 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: ?

Upvotes: 2

Views: 557

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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".

Upvotes: 4

Related Questions