How to validate input, in non-form element, on key

2020-04-30 18:00发布

问题:

I have a site that is being built in ASPX. Unfortunately, because of this fact, I cannot actually use the <form> tag to wrap my inputs, and as far as I can see, jQuery Validation Plugin only supports validating inputs within a <form>. Is there any way to validate these inputs, using the specified rules, on keyup without having them wrapped in a <form> tag?

$(function() {
  $('.form-container').validate({
    rules: {
      useremail: {
        required: true,
        email: true
      },
      userstate: {
        required: true,
        maxlength: 2
      }
    },
    messages: {
      useremail: 'Please enter a valid email',
      userstate: 'Please enter your state',
    }
  });
  
  $('.form-container input').on('keyup', function() {
    $(this).validate();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>

<div class="form-container">
  <input type="text" name="useremail" placeholder="Email" />
  <input type="text" name="userstate" placeholder="State" maxlength="2" />
</div>

回答1:

You cannot have nested forms, which is invalid HTML, and you must attach .validate() to a form container. There are no workarounds.

You're also using .validate() all wrong. Since this is the primary initialization method of the plugin, wrapping it within a keyup handler is not correct. Plus the plugin already uses the keyup event to trigger validation.

And no, you cannot put form input elements within a div and then target that div attached to .validate(). It will be ignored. You can only target form elements attached to .validate().

Furthermore, since you're using ASP, you can leverage its built-in Unobtrusive Validation plugin, which automatically constructs and calls the .validate() method based upon your data attributes. Just remember that if you follow this route, you cannot call .validate() yourself. The plugin only allows one call, and once initialized, all subsequent calls to .validate() are ignored.