Erwin O.
Erwin O.

Reputation: 309

How do I apply a required field validation only if one radio button is selected

I'm using MVC Data Anottation for client validations.

How do you implement this simple scenario:

Mark a field as required only if one radio button is selected

Upvotes: 4

Views: 5846

Answers (4)

Paweł Staniec
Paweł Staniec

Reputation: 3181

you wrote you're doing client side validation, so one way to accomplish your goal would be a simple javascript that would remove / modify validation rules attached to your input element:

$("#YourCheckBox").click(function(){ 
  if($(this).is(':checked')){
      $("#FirstName").rules("add","required")
  } else {
      $("#FirstName").rules("remove","required")
  }
});

you can find out more about validation plugin and its features here http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules

Of course you can easily find out more about jquery unobutrusive validation and do your variant. Thing to remember though is that you want to keep your client-side and backend validation consistent, so if you strip the [Required] from the model, you would have to check the value in your save/edit method.

Upvotes: 5

Karthik Chintala
Karthik Chintala

Reputation: 5545

As you did not post any code, i'm assuming your radio button field has the id rdbRequired and your field name say MyField.

Initially mark MyField as required.

Then in your controller, write like this:

 public ActionResult Index(MyModel model)
    {
       // If the radio button is not selected, MyField is marked as not required. I mean it is not validated
       if (model.rdbRequired == false)  
       {
            ModelState.Remove("MyField"); 
       }
       if(ModelState.IsValid){
       //do something
       }
       else{
             return View(model);
       }
    }

Hope this helps you

Upvotes: 0

heads5150
heads5150

Reputation: 7463

Look at using foolproof there is a RequiredIf attribute

private class Person
{
  [Required]
  public string FirstName { get; set; }

  [Required]
  public string LastName { get; set; }

  public bool Married { get; set; }

  [RequiredIfTrue("Married")]
  public string MaidenName { get; set; }
}

Upvotes: 2

DRobertE
DRobertE

Reputation: 3508

Try looking here, this should point you in the right direction.

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Upvotes: 0

Related Questions