DEV Community

Lakshya Tyagi
Lakshya Tyagi

Posted on

2 1

Only Numbers validation in JS

public numberOnlyValidation(event: any) {
    const pattern = /[0-9]/;
    let inputChar = String.fromCharCode(event.charCode);
    if (!pattern.test(inputChar)) {
        event.preventDefault();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
diek profile image
diek • Edited

Hi! Just giving you feedback. Your regexp not only pass numbers but every string containing at least one number.
Take a look at the ^ and $ reserved chars for regexp and think about the floating point your system is using.
Something like ^[\d]+$ for only integers.
Anyway, you can use isNaN and it's probably a better approach.
developer.mozilla.org/en-US/docs/W...

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay