I needed a JavaScript solution to automatically keep only valid characters (or, remove invalid characters) in a number field.

If the user types or pastes invalid characters into the input, this frontend script should remove them automatically.

The following does just that:

/**
 * Sanitizes the value of a number field and keeps digits only.
 */
document.querySelectorAll('.form-element.number').forEach((field) => {
	field.addEventListener('input', () => {
		field.value = field.value.replace(/[^0-9\.]/g, '');
	});
});

The event listener applies this sanitization to all number fields (elements with the form-element and number classes).

It rewrites the field value and removes non-numeric characters from it (e.g. test123abc becomes 123).

But, in some cases, I had to allow a plus sign (+) as well.

This was needed for international phone number fields: Fields that include a country dropdown menu that allows you to change the phone prefix (I use the “International Telephone Input” plugin for this).

However, only some of those tel inputs include this dropdown. So, numbers and a plus sign should be allowed if the field has a country dropdown (I added a country-dropdown data attribute to those). Otherwise, numbers only.

So I wrote this:

/**
 * Sanitizes the value of a number field and keeps valid characters only.
 */
document.querySelectorAll('.form-element.number').forEach((field) => {
	field.addEventListener('input', () => {
		// Allow only numbers.
		let regex = /[^0-9\.]/g;

		if (field.hasAttribute('data-country-dropdown')) {
			// Allow only numbers and a plus (for tel fields with a dropdown).
			regex = /[^+0-9\.]/g;
		}

		// Remove invalid characters.
		field.value = field.value.replace(regex, '');
	});
});

This sets the same regex from the previous script (which allows numbers only) as the default regex.

If the field includes the country-dropdown data attribute, the regex is changed to a version that also allows the plus sign.