Jadin Stojadin
Jadin Stojadin

Reputation: 225

Pattern HTML5 validation not preventing form submit when not validated

I have an odd problem where my pattern on two numerical fields is not working properly (the form can be submitted even if the fields are not validated). The HTML looks like following:

        <input type="text" class="txtmin" pattern="^[+-]?\d*(\.\d+)?$" placeholder="Minimum price">

        <input type="text" class="txtmax" pattern="^[+-]?\d*(\.\d+)?$" placeholder="Maximum price">

When I enter something into the field, if it doesn't matches the regex, the field gets marked red, but if I try to submit the form on onclick event, the validation doesn't prevents the user to change the input value and I get an exception ...

$(".btnAnalyze").click(function () {
            // the form doesn't validates??
        });

I was trying something like this:

  $('txtmin').oninvalid = function (event) {
            return;
        }

But this doesn't do anything? Can someone help me out?

Edit: Riyad this is the full code HTML and the event I'm firing:

<form>
     <span class="input-group-btn">
                            <button class="btn btn-default btnGo" type="submit">Go!</button>
                        </span>

</form>

  $(".btnGo").click(function () {

            if ($('.txtSearch').val() == "") {
                ShowMessage("Please enter the search term!");
                return;
            } 
            else{
                PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val());
            }
        });

Upvotes: 1

Views: 2040

Answers (2)

Bud Damyanov
Bud Damyanov

Reputation: 31839

If you expect only prices in your input fields, then better (i.e. most supported by browsers) approach is to use input of type number with min and max attributes:

<input type="number" class="txtmin" min="0.01" max="1000.00" placeholder="Minimum price">

<input type="number" class="txtmax" min="0.01" max="1000.00" placeholder="Maximum price">

Note that both fields have min and max attributes set, however this is not mandatory - you can restrict or not the values of every input with pure HTML this way.

Another approach is to use Javascript library like jQuery and perform manual validation of input.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Clicking the button doesn't equate to submitting the form. The order of actions is:

  1. Click the button
  2. Fire click event on the button
  3. If the click event does not cancel the event, then fire submit on the form
  4. If the submit event does not cancel the event (eg. validation errors!) then proceed to submit the form

Since you're doing your work in the click event, the form hasn't been validated yet! You should instead do the work in the form's submit event.

Upvotes: 1

Related Questions