DEV Community

Lakshya Tyagi
Lakshya Tyagi

Posted on

Only Numbers validation in JS

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

Top comments (1)

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.