0

I'm trying to validate an age field in a form but I'm having some problem. First I tried to make sure that the field will not be send empty. I don't know JavaScript so I searched some scripts and adapted them to this:

function isInteger (s)
{
  var i;
  if (isEmpty(s))
    if (isInteger.arguments.length == 1)
      return 0;
    else
      return (isInteger.arguments[1] == true);

  for (i = 0; i < s.length; i++)
  {
    var c = s.charAt(i);
    if (!isDigit(c))
      return false;
  }

  return true;
}

function isEmpty(s)
{
  return ((s == null) || (s.length == 0))
}

function validate_required(field,alerttxt)
{
  with (field)
  {
    if (value==null||value=="")
    {
      alert(alerttxt);return false;
    }
    else
    {
      return true;
    }
  }
}

function validate_form(thisform)
{
  with (thisform)
  {
    if  ((validate_required(age,"Age must be filled out!")==false) ||      
        isInteger(age,"Age must be an int number")==false))
    {email.focus();return false;}
  }
}

//html part
<form action="doador.php" onsubmit="return validate_form(this)" method="post">

It's working fine for empty fields, but if I type any letters or characters in age field, it'll be sent and saved a 0 in my database. Can anyone help me?

Sorry for any mistake in English, and thanks in advance for your help.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Marcelo
  • 1,503
  • 2
  • 15
  • 16
  • please indent your code next time. – vladv Jun 12 '10 at 18:05
  • 7
    pretty complicated functions for nothing, really. Check out this other answer: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric – vladv Jun 12 '10 at 18:10
  • 3
    Moreover, I don't think that “Age must be an int number” is a very helpful message to most visitors. Don't use technical terminology like ‘int’ or ‘integer’ on a website aimed at a non-technical audience. – Marcel Korpel Jun 12 '10 at 18:55

1 Answers1

2

You can use isNaN() to determine if an object is a number, for example:

someString="6";
someNumber=5;
someFloat=3.14;
someOtherString="The";
someObject = new Array();

isNaN(someString);      // Returns false
isNaN(someNumber);      // Returns false
isNaN(someFloat);       // Returns false
isNaN(someOtherString); // Returns true
isNaN(someObject);      // Returns true

Then you can use parseFloat() or parseInt() to convert a string into a number:

aString = "4";
aNumber = parseInt(aString);
if(aNumber<5)
    alert("You're too young to use this website");

See also this other question that vladv pointed out in the comments.

Community
  • 1
  • 1
Na7coldwater
  • 1,404
  • 12
  • 24