Regular expression for allow only numbers

javascript

You can use a regular expression to allow only numbers by matching the input string against a pattern that only allows digits.

The regular expression pattern to match only numbers is:

/^\d+$/

This pattern matches the beginning of the string ^, followed by one or more digits \d+, and then the end of the string $. The ^ and $ ensure that the pattern matches the entire string, not just a portion of it.

Here’s an example of how to use this pattern to validate a phone number input:

var phoneNumberInput = document.getElementById('phone-number');
var phoneNumber = phoneNumberInput.value;

if (/^\d+$/.test(phoneNumber)) {
  // Phone number is valid - only contains digits
} else {
  // Phone number is invalid - contains non-digit characters
}

In this example, we first get the value of the phone-number input element. We then use the test() method of the regular expression to check whether the input string contains only digits. If the regular expression pattern matches the input string, we know that the input only contains digits and is therefore valid. If the pattern doesn’t match the input string, we know that the input contains non-digit characters and is therefore invalid.