Reputation: 609
Is there a way to check if a text input, on change, has a number in the string without using regex and only using just javascript?
For example (this may not be a good approach, I am unsure):
const passwordInput = document.querySelector("#password");
passwordInput.addEventListener("change", e => {
if (e.target.value contains a number) {
console.log("Must contain a number.")
}
})
Upvotes: 1
Views: 540
Reputation: 18619
You can iterate over it, and check each character, you can use !isNaN(x)
to check if a x
can be converted to a number, and x.trim() !== ''
to filter out whitespaces (thanks to @Lain for pointing out that isNaN
returns false
for whitespaces):
function hasNumbers(string){
return Array.prototype.some.call(string, c => !isNaN(c) && c.trim())
}
const passwordInput = document.querySelector("#password");
passwordInput.addEventListener("change", e => {
if (hasNumbers(e.target.value)) {
console.log("Contains a number.")
} else {
console.log("Doesn't contain a number.")
}
})
<input id="password" >
Upvotes: 1