Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require validation only if the field is visible

Tags:

I am using the [Required] attribute for the client-side validation in ASP.NET MVC 3.

The class looks as:

public class User {     [Required(ErrorMessage = "First Name is required")]     public string FirstName { get; set; } } 

I want the field FirstName to be validated only if it's visible, which will be shown only on certain conditions. How can I do that?

I have used the following, but still it looks to validate for the required field of that hidden field.

$('#registerForm').validate({ ignore: ":not(:visible)" }); 
like image 798
Prasad Avatar asked Apr 20 '11 14:04

Prasad


People also ask

What is required field validation?

RequiredFieldValidator is basically doing validations against the required fields in the front end. The user must fill in all the mandatory fields, to ensure this we make use of RequiredFieldValidator.

How do I bypass required field validation in HTML?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

How do I turn off required field validator?

Well you can simple use the Enabled="false" property of RequiredFieldValidator .

Why do we need required field validator?

ASP.NET RequiredFieldValidator Control This validator is used to make an input control required. It will throw an error if user leaves input control empty. It is used to mandate form control required and restrict the user to provide data.


1 Answers

With some useful hints from @Josiah, i am able to get to my requirement.

Add the RequiredIfAttribute class and the required javascript. Refer Conditional Validation in ASP.NET MVC 3

And in the class add the RequiredIf attribute as:

public class User { [RequiredIf("hFirstName", "true", ErrorMessage = "First Name is required")] public string FirstName { get; set; } 

and in aspx:

@Html.TextBoxFor(model => Model.FirstName, new { @style = "height:auto;" }) @Html.ValidationMessageFor(model => Model.FirstName) @Html.Hidden("hFirstName") 

Set the value of hFirstName to 'true' if the FirstName field is hidden and 'false', if visible.

The magic works with these changes. Thanks to @Josiah Ruddell for his answer

like image 112
Prasad Avatar answered Oct 20 '22 00:10

Prasad