Table of Content
<input> elements of type number are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to allow the user to increase and decrease the value.
Occasionally situations arise (input a phone number, zip code or credit card number) when the user should fill a single or more than one fields with numbers (0-9) within an HTML form. It is possible to write JavaScript scripts to check the next validations.
– To check for all amounts in a field
– An integer with an optional leading plus(+) or minus(-) signal
Following code, blocks contain actual codes for the said validations. We’ve kept the CSS code part standard for all of the validation.
How to check all the numbers in a field?
To acquire a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only amounts. Then, the game () method of the string object is used to coincide with the stated regular expression contrary to the input value. Here’s the comprehensive web document.
Here’s the code to do it:
<form name="form1" action="#"> <ul> <li><input type='text' name='text1'/></li> <li class="rq">*Enter numbers only.</li> <li> </li> <li><input type="submit" name="submit" value="Submit" onclick="allnumeric(document.form1.text1)" /></li> <li> </li> </ul> </form>
function allnumeric(inputtxt) { var numbers = /^[0-9]+$/; if(inputtxt.value.match(numbers)) { alert('Your Registration number has accepted....'); document.form1.text1.focus(); return true; } else { alert('Please input numeric characters only'); document.form1.text1.focus(); return false; } }
How to get a number with a plus or minus signal?
To get a string contains only numbers (0-9) with an optional + or – sign we use the regular expression (/^[-+]?[0-9]+$/). Next, the match() method of the string object is used to match the said regular expression against the input value. Here is the complete web document.
<form name="form1" action="#"> <ul> <li><input type='text' name='text1'/></li> <li class="rq">*Enter numbers only.</li> <li> </li> <li><input type="submit" name="submit" value="Submit" onclick="allnumericplusminus(document.form1.text1)" /></li> <li> </li> </ul> </form>
function allnumericplusminus(inputtxt) { var numbers = /^[-+]?[0-9]+$/; if(inputtxt.value.match(numbers)) { alert('Correct...Try another'); document.form1.text1.focus(); return true; } else { alert('Please input correct format'); document.form1.text1.focus(); return false; } }