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:
The code copy is as follows:
var numRegex = //D/g
Then pass the onblur event in JavaScript:
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
HTML:
The code copy is as follows:
<element onblur="SomeJavaScriptCode">
JavaScript:
object.onblur= function(){//operate myScript; }In JavaScript, use the addEventListener() method:
The code copy is as follows:
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 is the relevant content that the editor introduces to you about using regular expressions and js restrictions that can only enter numbers. I hope it will be helpful to everyone, and I hope everyone will pay more attention to the Wulin.com website!