最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate in JS if an HTML5 input pattern has been matched? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Oct 10, 2017 at 13:55 blargblarg 3,90311 gold badges46 silver badges75 bronze badges 2
  • Simply add required to input tag – artgb 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. – alexhughesking Commented Oct 10, 2017 at 13:59
Add a ment  | 

2 Answers 2

Reset to default 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.

You can use the HTML5 constraint validation API (https://developer.mozilla/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>

发布评论

评论列表(0)

  1. 暂无评论