1

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.")
    }
})
ckingchris
  • 559
  • 1
  • 12
  • 25
  • 1
    You can check each character separately. – whatamidoingwithmylife Jun 05 '20 at 18:48
  • See https://stackoverflow.com/questions/5778020/check-whether-an-input-string-contains-a-number-in-javascript for solution. Please note that one digit is a "number". Just verify that this is what you want – Mulli Jun 05 '20 at 18:51
  • [Off-topic]: you can use the `input` event instead of `change` for instant checks – FZs Jun 05 '20 at 19:14

1 Answers1

1

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" >
FZs
  • 16,581
  • 13
  • 41
  • 50