Abhishek
Abhishek

Reputation: 997

Conditional Validation in MVC

In my application I want to implement the conditional validation and I am new to MVC. My code looks like this.

public class ConditionalValidation : IValidatableObject
    {
        public bool ValidateName { get; set; }
        public String Name { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (ValidateName)
            {
                if (string.IsNullOrEmpty(Name))
                {
                    yield return new ValidationResult("*");
                }
            }
        }
    }

But when I am accessing view of this no validation is working either I checked the checkbox or not and the page is submitting without checking the client side validation. I checked the ModelState.IsVlaid at the controller but is also true so please suggest where I am doing working.

Thanks

Upvotes: 0

Views: 707

Answers (1)

Alban
Alban

Reputation: 704

You need to add the required data annotation attributes.

Reference here: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx

Try this...

using System.ComponentModel.DataAnnotations;

public class ConditionalValidation : IValidatableObject
    {
        public bool ValidateName { get; set; }

        [Required(ErrorMessage=@"Name is required")]
        [Display(Name = "Name")]
        public String Name { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (ValidateName)
            {
                if (string.IsNullOrEmpty(Name))
                {
                    yield return new ValidationResult("*");
                }
            }
        }
    }

UPDATE: Also, make sure your web.config has the following in the <appSettings>:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

and that you have included the following on your page:
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

Here are some tutorials I found:
Unobtrusive Client Validation in ASP.NET MVC 3
Exercise 4: Using Unobtrusive jQuery at Client Side

Upvotes: 1

Related Questions