Reputation: 2174
i have this code for validating text field number.
This code works fine, but only problem is it does not allow me to enter .
(dot) .
My textfield is for amount, amount can be 222.234234 , or 222
So what code i should add in order to enable users to enter periods with the below scrits
function ValidateNum(input,event)
{
var keyCode = event.which ? event.which : event.keyCode;
if((parseInt(keyCode)>=48 && parseInt(keyCode)<=57) || parseInt(keyCode)==08 || parseInt(keyCode)==09 || parseInt(keyCode)==127 )
{
return true;
}
return false;
}
textfield
<input type="text" name="from_amount" onkeypress="return ValidateNum(this,event)" id="from_amount" placeholder=" Type to convert" />`
So please help me to solve this problem.
Upvotes: 0
Views: 1742
Reputation: 95518
Why not validate the entire string instead of validating each inputted character?
Do this:
//I am assuming that input is the text element
function validateNumber(input) {
//newer browsers should have .trim(). Otherwise you can do something like:
// input.value.replace(/^\s+|\s+$/g, "");
return /^\d+(\.\d+)?$/.test(input.value.trim());
}
Will your current validation-function account for the case when a use enters only the .
character? What about multiple .
characters? How about the value 123.
, or 1.43.3
, or 1..2
? It looks like the current function only validates the inputted character without looking at the context of that character (i.e., what surrounds it).
On another note, consider using something like jQuery or binding to the input element instead of using the onkeypress
attribute. That method of binding is more-or-less deprecated and not recommended. Also this method of validation prevents keypress events which can be confusing. It's probably better to validate the entire form after they have filled it in, or mark the text-field as invalid as they are writing in it.
You can also use the HTML5 type
value of number
instead of text
to constrain what the user can input into that field. That way you wouldn't even have to do any validation.
Upvotes: 1
Reputation: 7352
Keycode for .
is 190.
You can check this list here-> http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Upvotes: 1