0

I have the following form:

<form id="fromWiw" action="..." method="post">                    
  ...
  <div class="controls span5 pull-left">
      <label class="control-label" for="Quantity">@Resources.Quantity</label>
      <input class="span12" id="Quantity" name="Quantity" type="number" min="0" value="0" required />
  </div>
  <div class="controls span5 pull-left">
      <label class="control-label" for="Price">@Resources.Price</label>
      <input class="span12" id="Price" name="Price" required />
  </div>
  ...
</form>

For the validation part, I have this code snippet:

form.submit(function() {
    form.validate(
        {
            rules: {
                Quantity: { required: true, number: true},
                Price: { required: true, number: true }
            }
        });
});

PROBLEM The validation is working fine, it is detecting when the price and quantity are empty. However, the validation successfully passes when the price input contains non numeric values, text for example. The validation works fine for the Quantity input. Am I doing something wrong here?

Sparky
  • 98,165
  • 25
  • 199
  • 285
GETah
  • 20,922
  • 7
  • 61
  • 103

1 Answers1

2

Your code:

form.submit(function() {
    form.validate({
        ...
    })
})

"The validation works fine for the Quantity input. Am I doing something wrong here?"

Yes, you are.

.validate() is only the initialization method of the plugin on your form... it's not the testing method, and therefore does not belong inside of a submit handler. It should be called once on DOM ready instead. The plugin will automatically capture the submit event just fine.

$(document).ready(function() {

    $('#myform').validate({
        // rules & options
    });

});

You are also mixing HTML5 validation along with the Validation plugin.

There is no need to put the required attribute inside the HTML as well as declaring required within .validate(). The plugin will pick it up from either method; and when the plugin is used, it dynamically adds a novalidate="novalidate" attribute into the <form> tag to disable any HTML5 validation.

Working DEMO: http://jsfiddle.net/bNGQP/

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Yep it works fine. but now instead of having popovers I get inline error messages on my form. Any hints as to how the get the popovers back? – GETah Aug 02 '13 at 00:01
  • @GETah, the popovers are generated by HTML5 in your browser... they have nothing to do with the jQuery Validate plugin. Remove the plugin and you'll see. When using jQuery Validate, HTML5 validation is automatically disabled. See my edits. – Sparky Aug 02 '13 at 00:05
  • @GETah, if you want popovers with jQuery Validate, try Tooltipster. See the jsFiddle demos in this answer: http://stackoverflow.com/a/14741689/594235 – Sparky Aug 02 '13 at 00:16