Here I'm sharing some methods for text boxes(number type text boxes) to ensure that they only contain numbers.
The Primary and most basic method is to add an attribute type with value number to your input text box.
ie, <input type='number'/>,
this is very effective but on some occasions which will not give the proper output.
Here I would like to share a method using Java Script ,
to check a string is number you can use the following code
var isNum = /^\d+$/.test(value);
if(isNum)
alert(value + 'is a number');
else
alert(value + 'is not a number');
here 'value' is the input test sample,if the input string only contains the digits this code will alert that is a number.else which alerts that is not a number
eg:-
value = 5 output :- 5 is a number
value = jkljk output :- jkljk is not a number
value = h5ht output :- h5ht is not a number
value = #%$@ output :- #%$@ is not a number
which also detect the float number as not a number
ie,
value = 2.5 output :- 2.5 is not a number
so in case of float numbers we use a different script
var isFloatNumber = /^\d+\.\d+$/.test(value);
if(isFloatNumber){
alert(value + 'is a float number');
}
else {
alert(value + 'is not a float number');
}
eg:-
value = 2.5 output :- 2.5 is a float number
value = 5 output :- 5 is not a float number
value = jkljk output :- jkljk is not a float number
value = h5ht output :- h5ht is not a float number
value = #%$@ output :- #%$@ is not a float number

No comments:
Post a Comment