5

I have something like this:

<input type="text" id="number_field" pattern="[-+]?[0-9]*[.,]?[0-9]+" />

I can target custom css if the pattern is not matched using the :invalid selector.

I want to disable a submit button that makes an XHR if all the validation isn't met.

<button class="AdamBrown" onclick="saveAdamBrown(12)">Save</button>

How can I assess whether the pattern is met in Javascript?

2
  • Simply add required to input tag Commented Oct 10, 2017 at 13:59
  • 1
    You'd be better off putting the inputs in an actual form and using the form's submit event to know that validation passed. Commented Oct 10, 2017 at 13:59

2 Answers 2

6
var input = document.getElementById("number_field")
input.checkValidity()

checkValidity will simply return true or false. If you want to know why it fails validation, you can explore the input.validity object.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use the HTML5 constraint validation API (https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation ). You can check if you input pattern check is valid by checking the value of validity.patternMismatch of that element. Please see the snippet below with the example:

const saveAdamBrown = num => console.log(num);

var numberField = document.getElementById("number_field");
var button = document.getElementsByClassName('AdamBrown')[0];

numberField.addEventListener("input", function (event) {
   button.disabled = numberField.validity.patternMismatch;
});
<input type="text" id="number_field" pattern="[-+]?[0-9]*[.,]?[0-9]+" />
<button class="AdamBrown" onclick="saveAdamBrown(12)">Save</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.