It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming JavaScript Forum

Form Validation, not recognizing zero's

Form Validation, not recognizing zero's

Postby johnnyq on Fri Feb 05, 2010 3:16 pm

Hi,

I have a javascript function intended for form validation as follows:

Code: Select all

if(document.form1.textbox1.value > document.form1.textbox2.value)
      {
      alert('Please ensure text box 2 is greater than text box 1');
      return false;
      }

                return true;



This works to a certain extent, however it seems that javascript is ignoring the 0's i enter.

For example, when I enter 100 it will recognize this as 1. So that if I enter 20 in text box 1 and 100 in text box 2 it will give an error as it see's 2 is greater than 1.

Sorry if this seems stupid but I really cannot figure it out, any help would be greatly appreciated,
John
johnnyq
 
Posts: 4
Joined: Fri Jan 29, 2010 9:34 pm

Re: Form Validation, not recognizing zero's

Postby harrierdh on Fri Feb 05, 2010 7:57 pm

johnnyq,

The code you sent does not have any problems. It's got to be somewhere else. Can you post all your code or a link to your page? My only suggestion is that you make the textbox's into numbers. What you are comparing is string to string. Html does not return numbers. You need a numeric check, I've included one. Then use parseInt()
Top code is untested. Just off the top of my head. isNumeric() is tested.

Code: Select all
var text1 = document.form1.textbox1.value ;
var text2 = document.form1.textbox2.value;
if ((isNumeric(text1, false))&&(isNumeric(text2, false))) {
    var int1 = parseInt(text1);
    var int2 = parseInt(text2);
    if (int1 > int2) {
         alert('Please ensure text box 2 is greater than text box 1');
          return false;
      }
      return true;
}
alert("Please provide numeric values");
return false;

Code: Select all
<script language="javascript" type="text/javascript">
   function isNumeric(sText, decimalAllowed) {
      if (sText.length == 0) return false;
      var validChars = "";
      if (decimalAllowed) {
         validChars = "0123456789.";
      } else {
         validChars = "0123456789";
      }
      var isNumber = true;
      var charA;
      var decimalCount = 0;
      for (i = 0; i < sText.length && isNumber == true && decimalCount < 2; i++) {
         charA = sText.charAt(i);
         if (charA == ".") {
            decimalCount += 1;
         }
         if (validChars.indexOf(charA) == -1) {
         isNumber = false;
         }
      }
      return isNumber;
   }
</script>


harrierdh
50+ Club
 
Posts: 51
Joined: Wed Dec 16, 2009 7:04 pm


Who is online

Users browsing this forum: No registered users and 9 guests