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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay