24

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)" });
saluce
  • 13,035
  • 3
  • 50
  • 67
Prasad
  • 58,881
  • 64
  • 151
  • 199
  • I assume that, if you look carefully, you will find that adding the ignore instruction in javascript, stops client side validation. But on the post, server side validation kicks in and will return a page with validation messages. – R. Schreurs Mar 31 '17 at 09:50

4 Answers4

15

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

Community
  • 1
  • 1
Prasad
  • 58,881
  • 64
  • 151
  • 199
  • This thingy is so awesome! Simon Ince now has a Mvc.ValidationTookit Alpha Release here: http://blogs.msdn.com/b/simonince/archive/2011/09/29/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3.aspx! It should really be in a GitHub repo IMO. :) – Leniel Maccaferri Apr 30 '12 at 05:32
  • I finally got "RequiredIf" to work but I had to change the code a bit. For some reason it only worked if it extended RequiredAttribute instead of ValidationAttribute and another thing to point out is that the .addMethod on the client side needs to be outside the jQuery.ready() function. This is using C# 4.5, jQuery.validator 1.8.1 – Nick Apr 12 '13 at 08:45
7

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.

Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • Is there any custom attribute like RequiredIfVisible? In the FoolProof there are attributes like RequiredIf, RequiredIfNot, ..., i am not able to use them for my requirement. – Prasad Apr 20 '11 at 17:39
  • Not that I am aware of. But you can use a requiredif on a hidden field. Whatever is hiding/showing the content would simply update the hidden field as well. – Josiah Ruddell Apr 20 '11 at 19:00
1

Try my custom validation attribute:

[ConditionalRequired("hFirstName==true")]
public string FirstName {get, set};

It supports multiple conditions.

karaxuna
  • 26,752
  • 13
  • 82
  • 117
0

A bit late,

namespace System.ComponentModel.DataAnnotations
{
    public class RequiredIfVisibleAttribute : RequiredAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            if (HttpContext.Current.Request.Form.AllKeys.Contains(context.MemberName))
                return base.IsValid(value, context);

            return ValidationResult.Success;
        }
    }
}

But here's my solution.

Just an inheritance of Required that will act the same way, except that it will only activate if the field if included in the posted keys.

Bru
  • 21
  • 2