开发者

Validating age field

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜