Reputation: 59
I have an html input box, but only numeric data is data. How can I enforce that?
Upvotes: 4
Views: 21070
Reputation: 3993
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>
Upvotes: 0
Reputation: 4873
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):
Upvotes: 11
Reputation: 1
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);" />
Upvotes: -1
Reputation: 912
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');}" />
Upvotes: -1
Reputation: 6825
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.
Upvotes: 0
Reputation: 109
Use java script function as a validator. Or you can get the jquery funcations as well.
Upvotes: -2
Reputation: 15344
<input name="txtnumbersOnly" type="text" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">
Upvotes: -2