Sunday, June 11, 2006

Validating numeric fields in Javascript

Unless you use "Punctuated at thousands" field property of number fields, you can use following:
isnumeric=parseFloat(tmp)==(tmp*1)

But if you must have "Punctuated at thousands" property, the above code will not work properly.
For example, 20 000,00 is not the same as 20000,00.
The "space" character in the number is not a regular space, but a special separator. It's ASCII code is 160. This special character makes the validation code above work incorrectly.

Here is how you can validate such field without changing it's properties:

Code to put in onBlur event of the field:
isNumber(this, "Product Price"); // pass field handle and field title

Code to put on Form or in JSHeader:
< script >
function isNumber(obj, title){
if(typeof obj=="undefined" || obj.value.length==0){
return true;
}
tmp="";i=0;
sText=obj.value.replace(".", ","); //replace dot to comma, which is decimal separator
for(i=0; i <= sText.length; i++){
if(sText.charAt(i).length!=0){
if(sText.charCodeAt(i)!=160 && sText.charCodeAt(i)!=32){ // remove thousands space and regular space
tmp=tmp+sText.substring(i,i+1);
}
}
}
obj.value=tmp;
tmp=tmp.replace(",", ".").replace(" ", ""); //replace dot to comma and remove space
res=(parseFloat(tmp)==(tmp*1));
if(res==false){
alert(title+" field must be numeric!");
obj.focus();
};
return res;
}
< /script >

1 comment:

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.