简体   繁体   中英

jQuery .validate rules don't appear to be applying? (jsfiddle)

http://jsfiddle.net/sK9tL/1/

When I manually add the rule()'s in the console on my form page, it appears to validate as expected.

I'm not sure if there is something wrong with the way I am formatting this?

$('#freeFormAdd').validate({
        rules:{
            freeFormName: {
                required: true, 
            },
            freeFormPrice: {
                required: true, 
            },
            freeFormQty: {
                required: true, 
            }
        }
    });

Then I use the .valid() to determine if the form is ready to submit. Since the page is "seamless" I don't need the form to submit, just to add some items to a cart (which is commented out in the jsfiddle).

Any advice?

Your form elements should have name attribute not id attribute, validator selects the elements based on their name attributes. Also instead of listening to the click event, you can use the submitHandler method:

 $('#freeFormAdd').validate({
     rules: {
         freeFormName: {
             required: true,
         },
         freeFormPrice: {
             required: true,
         },
         freeFormQty: {
             required: true,
         }
     },
     submitHandler: function () {
         alert('the form is valid');
     }
 });

Please note that I have moved the button to the form element's context so it triggers the submit event.

http://jsfiddle.net/QU3XM/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM