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.")
    }
})
3
  • 1
    You can check each character separately. Commented Jun 5, 2020 at 18:48
  • See stackoverflow.com/questions/5778020/… for solution. Please note that one digit is a "number". Just verify that this is what you want Commented Jun 5, 2020 at 18:51
  • [Off-topic]: you can use the input event instead of change for instant checks Commented Jun 5, 2020 at 19:14

1 Answer 1

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" >

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

1 Comment

Sure: !isNaN(' ')

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.