[RESOLVED]How to validate specific textbox fields using asp.net mvc 4

Hello all,

I have created a simple asp.net MVC form. I have five fields and one radio button list having values Yes and No on this form.

When i click on radio button Yes value i want to validate first three fields, but when i click on No i want to validate other two fields but not the first three. How can i achieve this according to above scenario?

Thanks.

Hi there

You can do this by creating a customised Validate method in your model class. Remember to make your model class implement IValidateObject.

public class MyModel : IValidatableObject
{
    public bool YesOrNo { get; set; }
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
    public string Value4 { get; set; }
    public string Value5 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
        if (YesOrNo)
        {
             // Validate first 3 fields

             // If, for example, Value1 fails, use this line:
             yield return new ValidationResult("Error!", , new[] { "Value1" });
        }
        else
        {
            // Validate  other 2 fields

            // If Value 4 fails, use this line:
            yield return new ValidationResult("Error!", new[] { "Value4" });
        }
    }
}

Let me know if you need more details.

Write following code on radio button click.

$("#formID").valid();

This will validate all the controls inside form.

Thanks for the reply,
I have some confusion in ur code. First of all please explain following line of code word by word:
public IEnumerable<ValidationResult> Validate(ValidationContext context)

Secondly I have to validate on button click so how can I fit ur code on button click, thanks.

That line is just a declaration for a method on your model class. It returns a collection of ValidationResults to the ModelState in your controller. The ValidationContext that is passed in happens automatically. Because you’re implementing the IValidateObject
interface you need that signature but in this case you don’t need the context so just ignore it. 

As for making it validate on button click, well that means you either want to forget my suggestion and just validate with Javascript, or if you want it to validate server side (on post back) then just add a submit button and ensure your form action matches
the action in your MVC controller. 

Hi Rauf,

For these requirement, you could use MVC Foolproof Validation (RequiredIF etc…).

More information, please refer to:

# MVC Foolproof Validation

http://foolproof.codeplex.com/

You also could custom validation to achieve that.

About custom validation, please refer to:

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Best Regards

Starain Chen

For this scenario , I Jquery validation is the best solution

Jquery validation :

$(document).ready(function () {
var isChecked = jQuery("input[name=radiobtnYes]:checked").val();
     if(!isChecked){
         /// Check validation for No
     }else{
         /// Check validation for Yes
     }
}); 
Thanks for ur reply,
Your idea look good to me. But for example if I have 20 textboxes then shall I have to write validation rule for every texbox? Is there not any other way or out of the box way like mvc unobstrusive validation in which we just write [required] in model class
and everything done! I just want that i should not write many lines for every textbox for validation, thanks.

Hi Rauf,

After you custom the validation, you could use it to those fields/properties, it is the same as
required. So, you don’t need have multiple validation for these fields/properties.

Best Regards

Starain Chen

Really your requirement of conditional validation means you’re going to need some customized code. Your options are:

Customized Validate method (as per my first post)

Customized Attribute

Javascript

Another javascript option is jquery validate (http://jqueryvalidation.org/)

I recommend this as something you should look into anyway, it’s not hugely complicated and allows you to do the kind of customized validation you’re trying to do quite easily, without needing to know too much javascript (you just need to read through the
documentation). You can use it in lots of projects!

You can set "depends" on your options to a jquery function which checks if they should be validated. There’s an example here:

https://stackoverflow.com/questions/379838/using-depends-with-the-jquery-validation-plugin

Leave a Reply