0

Here is my problem.
I have a razor generated form that has multiple fields but I want email to only be required if the System Admin radio button is clicked. It is defaulted to system user.

<div class="">@Html.LabelFor(m => m.Email)</div>
     <div class="">
          @Html.TextBoxFor(m => m.Email, new { @class = "form-control required", placeholder = "Email" })
          @Html.ValidationMessageFor(m => m.Email)
     </div>

I even tried removing the "required" after form control and taking out the validation.

I have 2 radio buttons that are generated by razor that have the same name but different values.

<div class="inline-editor create-user-roles">
    <input id="UserRole" name="UserRole" type="radio" value="System Administrator">
    <input id="UserRole" name="UserRole" type="radio" value="System User">
</div>

Here is the JQuery function that I am trying to use.

$('input[name="UserRole"]').on('change', function () {
    if ($('input[name="UserRole"]:checked').val() == "System Administrator") {
        $('#Email').rules('add', {
            required: true, messages: { required: "This field is required" }
        });
    }
    else {
        $('#Email').rules('add', {
            required: false
        });
    }
});
jgabb
  • 542
  • 1
  • 4
  • 20
  • you need to update your js like this `if($(this).is(':checked') && $(this).val() == 'System Administrator')` and replace `click` with `change` – Sushil Sep 29 '15 at 16:51
  • That doesn't seem to do the trick. It's still letting me submit the form without an email @Sushil – jgabb Sep 29 '15 at 17:10
  • 1
    first of all you have multiple elements with the same id. that needs to go. then instead of using `$('#UserRole').click` try using `$('input[name="UserRole"]').on('change', function())` – Sushil Sep 29 '15 at 17:17
  • 1
    Yeah, it's not valid to have multiple elements with the same `id`. The `id` attributes need to be unique, even if the `name` attributes are the same. – Chris Pratt Sep 29 '15 at 17:26
  • I attempted another js function that i just added but that didn't seem to fix the problem either. – jgabb Sep 29 '15 at 17:37
  • I simplified my js and checked it in the console. I think maybe its a problem with adding the rules? – jgabb Sep 29 '15 at 17:49
  • you dont need to write this again `$('input[name="UserRole"]:checked')`. instead just use `if($(this).is(':checked') && $(this).val() == 'System Administrator')` – Sushil Sep 29 '15 at 18:19
  • You could use a [RequiredIf attribute][1]. [1]: http://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute – Andy Wiesendanger Sep 29 '15 at 19:47

2 Answers2

0

I'm assuming you are using jQueryValidation [from the syntax]. Changing your code to the following should do the trick:

$('input[name="UserRole"]').on('change', function () {
if ($(this).is(':checked') && $(this).val() == "System Administrator") {  // `this` refers to the current element that has raised the event, i.e. shorter for `input[name="UserRole"]` in this case
   $('#Email').rules('add', {
        required: true, messages: { required: "This field is required" }
       });
   }
   else {
       $('#Email').rules('remove');  // Take note of this part
   }
});

Notice that you need to remove the rule. Specifying false on a particular rule will not have any effect on removing it.

Update: Using the .rules() method on form elements requires that you have already invoked the .validate() method [with an empty object] on the form.

That is, add the following line before the above block of code:

$('#yourFormId').validate({});

//rest of your code where you can add your validation rules with `.rule()`.
Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
  • I appreciate your effort but that still does not work. I am still able to submit a form without an email with the system admin button checked. – jgabb Sep 29 '15 at 18:59
  • Thanks. I tried this as well but to no avail. I posted an answer that I got to work. Thanks for your help! – jgabb Sep 29 '15 at 20:05
  • Will your method prevent the form from being submitted as I see you're neither returning `false` nor doing `e.preventDefault()` on the submit handler. – Ahmad Baktash Hayeri Sep 29 '15 at 20:13
0

Okay so I figured it out. I found a simpler way of doing it that solved all my problems. Here is is!

$('input[name="UserRole"]').on('change', function () {
    if ($('input[name="UserRole"]:checked').val() == "System Administrator")     {
        $("#Email").removeClass('form-control').addClass('form-control required');
    }
    else {
        $("#Email").removeClass('form-control required').addClass('form-control');
        $("span[for^='Email']").remove();
    }
});
jgabb
  • 542
  • 1
  • 4
  • 20
  • This will not really solve anything since you need to repeat the logic again in the server. Consider using a [foolproof](http://foolproof.codeplex.com/) `[RequiredIf("UserRole", "System Administrator")]` or similar attribute so you get both client and server side validation out of the box. –  Sep 30 '15 at 00:12