1

JS:

validate document.forms();

if (document.forms[0].userAge.value == "") {
    alert("Age field cannot be empty.");
     return false;
}


if (document.forms[0].userAge.value < 5) {
  alert("Your age input is not correct.");
  return false;
}


if (userage == isNumber) {
  alert("Your age input is not correct.");
  return false;
}

alert("Name and Age are valid.");
return true;

HTML:

     <label for="userAge">Age:</label>

    <input type="text" name="userAge" id="userAge" />

 </div>

If this is the code I have, how would I make it so that if someone were to enter a non number in the age text box an alert would come up saying " Your input is not correct"?

Michiel Kalkman
  • 3,054
  • 24
  • 25
jonathan miller
  • 2,919
  • 2
  • 14
  • 6
  • it kept saying while i was trying to post the question that I had code in my question that I had to format so i eventually just took out the syntax so i could post the question – jonathan miller Apr 21 '12 at 04:56
  • 2
    @jonathanmiller all you have to do is highlight your code and then use Ctrl+K or click the `{}` in the toolbar above the textarea for code boxes - no need to remove important parts of the code. – Nathan Apr 21 '12 at 05:05
  • i did both of those things and it did not work – jonathan miller Apr 21 '12 at 05:15
  • 1
    @jonathanmiller, you probably should break `html` and `javascript` in 2 independent code-blocks, not one. (Or use ` – Aleksei Zabrodskii Apr 24 '12 at 00:29

4 Answers4

2

Edit: I originally suggested using parseInt with isNaN() to test if the input was non-numeric. Well, it seems that using a regex is preferrable not only formatching cases like "4a" correctly, but it's actually faster in many cases (surprise!).

I mocked up some HTML with a button to illustrate.

HTML:

<form>
    <label for="userAge">Age:</label>
    <input type="text" name="userAge" id="userAge" />
    <input type="button" id="test" name="test" value="Test" />
</form>

JavaScript:

function validateForm() {

    // get the input value once and use a variable
    // this makes the rest of the code more readable
    // and has a small performance benefit in retrieving
    // the input value once
    var userAge = document.forms[0].userAge.value;

    // is it blank?
    if (userAge === "") {
        alert("Age field cannot be empty.")
        return false;
    }

    // is it a valid number? testing for positive integers
    if (!userAge.match(/^\d+$/)) {
        alert("Your age input is not correct.")
        return false;
    }

    // you could also test parseInt(userAge, 10) < 5
    if (userAge < 5) {
        alert("Your age input is not correct.")
        return false;
    }

    alert("Name and Age are valid.");
    return true;
}

// trigger validateForm() however you want, I did this as an example
document.getElementById("test").onclick = validateForm;

​Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/m2spX/6/

About the regex: userAge.match(/^\d+$/) returns true if userAge only contains a positive integer. The beginning / and ending / indicate a regular expression literal. \d indicates ASCII digits only. + matches one or more occurrences of the previous pattern (digits in this case). ^ indicates match from the beginning, and $ indicates match until the end. So /^\d+$/ is a regex literal matching only ASCII digits from beginning to end!

Also note that you can combine the last two if statements using an OR operator (||). I left these isolated in case you want to give each one a unique validation message.

It would look like this:

if (!userAge.match(/^\d+$/) || userAge < 5) {
    alert("Your age input is not correct.")
    return false;
}

Feel free to ask any questions about the code and I will explain. I hope that helps!

Will Klein
  • 2,244
  • 17
  • 18
  • Please note, you could skip using parseInt() and just use userAge everywhere. However, if the requirements changed you could get weird behavior, particularly if you try isNaN with an empty string if the field became optional. You could also combine the last two if statements, I left them separate for clarity's sake. – Will Klein Apr 21 '12 at 18:33
  • 1
    You should probably check for `NaN`-value before comparing it with 5. (Anyway, `false === (NaN < 5)`.) Also, note, that `parseInt` will return `number`, when given something like `14asd, 10` as arguments. Don't know how to solve this issue, though. Probably it is OK to just replace html-input's value with parsed number `.toString()` result. – Aleksei Zabrodskii Apr 24 '12 at 00:31
  • I agree. I thought about that too but left it as is. I wanted to keep it simple, but you are completely correct about that. – Will Klein Apr 24 '12 at 02:51
  • Well if it's not getting any votes and it's not getting accepted, I might as well make it correct. I moved the isNaN() check up. You're also right about mixed characters parsing as valid numbers. A regex would be an easy way to test this. ^_^ – Will Klein Apr 24 '12 at 03:01
  • Ok, I decided to add in the regex and I also learned it's actually faster than parseInt()/isNaN() for most browsers, and almost as fast when it's not. I took out parseInt altogether, to simplify that aspect. Thanks for chiming in elmigranto. – Will Klein Apr 24 '12 at 03:33
1

I recommend you to use the following Javascript which will not allow non-numeric characters in the text field.

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
        return false;
    }
    return true;
}

<input type="text" id="userAge" name="userAge" onkeypress="return isNumberKey(event);">
Lion
  • 18,729
  • 22
  • 80
  • 110
1

Try this solution

   <script language="javascript">
   function validate(){
  alert("validate ..."+document.forms[0].userAge.value);
  if (document.forms[0].userAge.value == ""){ 
    alert("Age field cannot be empty.");
    return false;
  }

  if (document.forms[0].userAge.value<5){
    alert("Your age input is not correct.");
    return false;
  }
   //provide a way to validate if its numeric number..maybe using regexp
   //if (isNumeric(userAge)){
   //   alert("Your age input is not correct.");
   //   return false;
   //}
   //alert"Name and Age are valid."
   return true;
  }
    </script>

The HTML should be

<form>
<div><label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" onblur="validate()"/>
</div>
</form>
Sanath
  • 4,774
  • 10
  • 51
  • 81
  • http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric for numeric validation.. – Sanath Apr 21 '12 at 05:11
1

use the code below

  if(isNaN(document.forms[0].userAge.value)){
     alert('This is not a number');


  }
EBIWARI
  • 43
  • 1
  • 6