When we register an account on some websites and fill in information, we accidentally fill in the phone number into Chinese characters or other English letters, this is obviously incorrect. In order to help users better correct errors in input, when filling in information in the form, it is necessary to restrict text boxes such as mobile phone number, zip code, and phone number from entering other characters, only numbers.
By using regular matching inputs, just numbers:
var numRegex = //D/g and then through JavaScript
onblur event:
Definition and usage
The onblur event occurs when the object loses focus.
Onblur is often used in Javascript verification code, and is generally used in form input boxes.
grammar
In HTML:
<element onblur="SomeJavaScriptCode">
JavaScript:
object.onblur= function(){ //Operate myScript; }In JavaScript, use the addEventListener() method:
object.addEventListener('blur',myScript);
Final DEMO code:
var numRegexFn = function(obj){ obj.value = obj.value.replace(numRegex,''); if(!obj.value){ alert('Please enter a number'); }else{ alert('pass'); } } phone.onblur = function(){ numRegexFn(this);}The above implementation code that can only enter numbers is the entire content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.