1

I have a form with an email field and a "get newsletter" checkbox.

<form method="post" class="form-horizontal" action="">

<input class="form-control" type="text" id="Email" name="Email" value="[email protected]" />
<span class="text-danger field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>

<input data-val="true" id="GetNewsletter" name="GetNewsletter" type="checkbox" value="true" />

</form>

The email field is initially optional, but required if user checks the get newsletter checkbox. I added this on client side using jquery validation.

$("#GetNewsletter").change(function () {
    var checked = $(this).prop("checked");
    if (checked) {
        $('#Email').rules('add', {  //set required rule
            required: true,
            messages: {
                required: "Email is required."
            }
        });
    }
    else {
        $('#Email').rules('remove', 'required'); //remove rule and call valid()
        $('#Email').valid();
    }
});

If the checkbox is unchecked, I remove the rule and call valid() to reset the status of the input. Unfortunately, this does not remove the validation message.

Is there a built-in way to clear the validation message? I want to avoid manipulating the markup, e.g. remove/add validation classes.

3
  • 1
    Something else is wrong. Calling .valid() after removing the rule should remove the message. Commented Nov 7, 2017 at 15:11
  • Can you? Seriously, the burden is on you to properly demonstrate the issue. Commented Nov 7, 2017 at 15:30
  • 1
    DEMO: jsfiddle.net/zh5uofs9 Commented Nov 7, 2017 at 17:27

2 Answers 2

1

Your (unsuccessful) attempt would only be removing the error message in the view and you would still need to write code in your controller method to validate the data (client side validation is a nice bonus but it can easily be bypassed you must validate on the server).

Instead, use a conditional ValidationAttribute that implements IClientValidatable so that you get both client and server side validation. An example of such an attribute is the foolproof [RequiredIf] or [RequiredIfTrue] attribute which you would apply to your model as

[RequiredIfTrue("GetNewsletter", ErrorMessage = "...")]
public string Email { get; set; }

and then in the view

@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)

@Html.CheckBoxFor(m => m.GetNewsletter)

If the checkbox is checked, and Email is empty, then a validation message will be displayed (and if client side validation is bypassed, then ModelState will be invalid in the POST method.

Alternatively, if you want to write your own conditional validation attributes, refer The Complete Guide To Validation In ASP.NET MVC 3 - Part 2 for a good guide.

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

Comments

1

You can only dynamically add/remove rules that were added with one the plugin's methods1.

$('form').validate({
    rules: {
        Email: {
            required: true
        }
    }
});

DEMO: jsfiddle.net/zh5uofs9/

If you have anything else making it required, such as inline attributes2 , then you will not be able to use .rules('remove')1.

DEMO 2: jsfiddle.net/zh5uofs9/1/


1 As per the documentation:

"Manipulates only rules specified via rules-option or via rules("add")."

2 Since you're using ASP, your instance of .validate() is being automatically constructed by the Unobtrusive Validation plugin and you have inline attributes declaring the rules.

Bottom line: The message will not clear because the rule is not being removed. And you cannot dynamically disable or remove the rule while using inline validation attributes.

Comments

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.