I have an html input box, but only numeric data is data. How can I enforce that?
7 Answers
You can use HTML5 to validate the type of your input without using JavaScript. However, this method is not (yet) supported by all browsers.
<input type="number" name="quantity" min="1" max="5">
Use the following attributes to specify restrictions (as described here):
- max - specifies the maximum value allowed
- min - specifies the minimum value allowed
- step - specifies the legal number intervals
- value - Specifies the default value
2 Comments
You will need an events to validate if the entered text is a number or not. See sample code
JS
function isValidChar(char){
var txt = char;
var found = false;
var validChars = "0123456789"; //List of valid characters
for(j=0;j<txt.length;j++){ //Will look through the value of text
var c = txt.charAt(j);
found = false;
for(x=0;x<validChars.length;x++){
if(c==validChars.charAt(x)){
found=true;
break;
}
}
if(!found){
//If invalid character is found remove it and return the valid character(s).
document.getElementById('txtFld').value = char.substring(0, char.length -1);
break;
}
}
}
HTML
<input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />
See working code here jsfiddle
Though the code is a bit long you can minimize if you know how to use regular expression or a jquery.
3 Comments
onKeyPress="isValidChar(this.value);" will solve that problem. Thanks for the information I'll check my existing code to fix for a possible effect in my application.Try this and it is up to you to select the minimum number and maximum:
legend {
background-color: #000;
color: #fff;
padding: 3px 6px;
}
.output {
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
width: 43%;
}
input {
margin: 1rem 0;
}
label {
display: inline-block;
font-size: .8rem;
}
input:invalid + span:after {
content: '✖';
color: #f00;
padding-left: 5px;
}
input:valid + span:after {
content: '✓';
color: #26b72b;
padding-left: 5px;
}
<span class="validity"></span>
<input type="number" id="userId" name="userId"
placeholder="Min: 1, max: 10000"
min="1" max="10000" />
<span class="validity"></span>
Comments
Number() is the function you want "123a" returns NAN
parseInt() truncates trailing letters "123a" returns 123
<input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" />
2 Comments
javascript: pseudo-protocol, this is not needed at all since Netscape...Try this code. work even on ctrl+v(paste)...
<SCRIPT Language ="VBScript">
sub onlyNumber(idBox)
Set objInl = CreateObject("VBScript.RegExp")
objInl.Global = True
objInl.Pattern = "[^0-9\-\.]"
document.getElementById(idBox).value = objInl.Replace(document.getElementById(idBox).value, "")
set objInl = nothing
end sub
</SCRIPT>
<input type="text" id="txtFld" onKeyup="onlyNumber(this.id);" />