I am trying to dynamically add a regular expression (for accepting only positive integers) to an html input text field also created dynamically, using the following, but which does not work:
text.setAttribute('pattern', '^[1-9]\d*$')
or
text.setAttribute('pattern', '[1-9][0-9]*')
But the pattern is not being reinforced. Any characters are accepted.
Resolution: In order to set the attribute and a function dynamically, as explained below by Can, one needs to add it as the following:
text.addEventListener('keyup', () => this.validate())
It is also possible to use:
text.addEventListener('focusout', () => this.validate())
I figured it out, it's actually that the \
character is escaping the character after it. You need to escape the backslash to make the pattern work.
const f = document.getElementById('form'); const p = '\\d\\d\\d'; const btn = document.getElementById('btn'); const txt = document.getElementById('text'); f.onsubmit = (e) => { e.preventDefault(); } btn.onclick = () => { txt.setAttribute('pattern', p); }
<form id="form" action=""> <input type="text" id="text"> <button type="submit"> Go </button> </form> <p> <button id="btn"> Add Pattern </button> </p>
You need to create an function and run that with something like onkeyup:
(function() {
var previousValue = document.getElementById('myInput').value;
var pattern = /^\d+$/;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
console.log(newValue.match(pattern));
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').onkeyup = validateInput;
}());
Check the example on jsfiddle
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.