jquery validation plugin - not validating on submit

前端 未结 2 560
故里飘歌
故里飘歌 2021-01-29 00:00

I\'ve got a form with several fields, some of which I\'d like to have validated on keyup and on submit. I am calling jquery 1.9.1 then the plugin (1.11.1), then an external fil

2条回答
  •  旧巷少年郎
    2021-01-29 01:03

    You have several problems...

    1. "If I add this piece of code in the beginning:" $("#untForm").submit(function() {

    You absolutely do not need to add a submit handler. The plugin already captures the click of the submit button and handles everything automatically.

    1. Your code must be enclosed within a DOM ready handler to ensure the HTML markup for the form exists when you call the .validate() method. (This omission explains why nothing was working until you enclosed it within a submit() handler.)

    2. The onfocusout option is activated by default. As per the documentation, setting it to true "is not a valid value". (Setting it to true can break things.) If you want this option, you must leave out onfocusout: true because it's already the default.

    3. The rules with boolean parameters, such as required, do not get quotation marks around the true parameter.

      required: true
      
    4. Not sure why you have required: false on the attachment field. If you don't specify the required rule, then the field is not required (it's optional). There's no purpose in setting it to false when leaving it out achieves the same.

    5. Based on your parameters of "jp?g,png,gif,txt", I'm not sure you intended to use the accept rule, which is for MIME Types. Those look like file extensions, and in that case, you should be using the extension rule instead. If that's the case, they need to be separated with a | character. See: http://jqueryvalidation.org/extension-method/

    6. When you use the accept or extension rules, you must include the additional-methods.js file, just in case you haven't.

    7. Not sure what you meant by "not validated" on the cc_email field. You've only defined the email rule so when you enter an non-email address, it will give you an error. However, you did not specify the required rule so this field will be optional. If you want it mandatory, then add required.

      cc_email: {
          required: true,
          email: true
      }
      

    DEMO: http://jsfiddle.net/ca2Rd/

    DEMO with your markup: http://jsfiddle.net/mECS9/


    HTML markup issues.

    1. elements are not containers, do not have a closing tag, and you cannot put other elements inside of them. They are stand-alone and self-closing, similar to a
      tag.

    NOT valid: ...

    NOT valid:

    Valid:

    Valid:

    1. You do not need the required attribute inside of the