Thursday, May 3, 2012

Required validation only if the field is visible in asp.net mvc


I am using the [Required] attribute for the Clientside 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 on if its visible, which will be shown only on certain consition. 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)" });


Source: Tips4all

2 comments:

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

    ReplyDelete
  2. I would create a conditionally required attribute. There is a good article on creating one with jQuery validation here.

    Another option: you could reference a project like Foolproof validation (codeplex) that provides this functionality and the client scripts.

    Additionally you could utilize ajax to load your partial views so that they are never on the page when hidden. This would avoid conditional validation altogether.

    ReplyDelete