0

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

1
  • Well i checked it is working on the server side but as we use simple validations on the model, the mvc framework automatically generate client side validations but in this case not. so there is any way to generate it from the model instead of writing the self javascript validation ? Commented Oct 17, 2011 at 8:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Its good and but now working on the client side. is there other stuff i have to add for the client side ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.