Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery Validation: Changing Rules Dynamically
    primarykey
    data
    text
    <p>I have a single form that, depending on which radio button is clicked (Login or Signup), displays either:</p> <ul> <li>email address</li> <li>password</li> </ul> <p>or:</p> <ul> <li>name</li> <li>age</li> <li>email address</li> <li>password</li> </ul> <p>Clicking on the radio button toggles the visibility of the Login/Signup fields:</p> <pre><code>&lt;form id="myForm"&gt; &lt;input name="userAction" type="radio" value="login" checked="checked"&gt;Login&lt;/input&gt; &lt;br /&gt; &lt;input name="userAction" type="radio" value="signup"&gt;Sign Up&lt;/input&gt; &lt;div id="loginFields" style="display:none"&gt; &lt;!-- Login fields (email address and password) --&gt; &lt;/div&gt; &lt;div id="signupFields" style="display:none"&gt; &lt;!-- Signup fields (name, age, email address, password) --&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I'm using the <a href="http://docs.jquery.com/Plugins/validation" rel="noreferrer">jQuery Validation plug-in</a>, and I'd like to use the following rules:</p> <pre><code>var signupRules = { emailAddressTextBox: { required: true, email: true }, passwordTextBox: { required: true, minlength: 6, maxlength: 24, passwordValidationRule: true // custom regex added with $.validator.addMethod() } }; var loginRules = { nameTextBox: { required: true, maxlength: 50 }, loginEmailAddressTextBox: { required: true, email: true }, loginPasswordTextBox: { required: true, minlength: 6, maxlength: 24, passwordValidationRule: true // custom regex added with $.validator.addMethod() }, loginPasswordAgainTextBox: { required: true, minlength: 6, maxlength: 24, equalTo: "#loginPasswordTextBox" passwordValidationRule: true // custom regex added with $.validator.addMethod() } }; </code></pre> <p>How can I add the correct validation rule dynamically based on:</p> <pre><code> $("input[name='userAction']").change(function() { if ($("input[name='userAction']:checked" ).val() === "login") { // use loginRules } else { // use signupRules } }); </code></pre> <p>I've tried the following:</p> <pre><code>$("#myForm").validate({ rules: ($("input[name='userAction']:checked" ).val() === "login") ? loginRules : signupRules; }); </code></pre> <p>But since my Login fields are the default displayed, its validations work, but the Signup scenario doesn't; it wants to validate Login fields for some reason. Am I missing something?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload