The code below validate two nameserver textbox. As you can see there is redundancy in the javascript code. // validate textbox 1 and // validate textbox 2. Is there anyway I could just use one script.. you know I just want to use 1 validation function to validate two textbox. I'm sorry for my English I hope you all can understand me. Thank you.
<script type="text/javascript">
// validate textbox 1
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
// validate textbox 2
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver2.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver2').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver2').focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>
Well here is another approach:
function ValidateDomain(){
function CheckForBlank(domain, textBox){
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
}
function CheckForFormat(domain, textBox){
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
function GetDomainName(inputId){
var serverName = document.getElementById(inputId).value,
domain_array = serverName.split('.');
return domain_array[0];
}
var nameserver1 = GetDomainName('nameserver1'),
nameserver2 = GetDomainName('nameserver2'),
nameServerInput1 = document.getElementsById('nameserver1');
nameServerInput2 = document.getElementsById('nameserver2');
if (CheckForFormat(nameserver1,nameServerInput1) && CheckForBlank(nameserver1,nameServerInput1)
&& CheckForFormat(nameserver2,nameServerInput2) && CheckForBlank(nameserver2,nameServerInput2)){
//This means you are valid
return {
name1:nameserver1,
name2:nameserver2
}
}
return false;
}
Maybe like this:
<script type="text/javascript">
function validate_domain(){
validateTextBox('nameserver1');
validateTextBox('nameserver2');
}
function validateTextBox(tbName){
var nameserver1 = document.getElementById(tbName).value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(tbName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(tbName).focus();
return false;
}
}
}
</script>
Saw this one at work. Played with it at home. Here's a working jsFiddle. Yes, it's overly complex, but I detest alert('annoying pop-up');.
I commented the source, so you would better understand why I wrote it like that.
sg522: It may not copy/paste into your code and work, but I don't know what the rest of your code is. Neither are we here to write your code for you. We are here to help you learn and become a more experienced programmer.
Please let us know if you have questions.
Happy coding!
UPDATE: Modified jsFiddle to work with Opera and Firefox 10.
Neither Opera or Firefox apparently allow cloneNode to be called without parameters now.
Opera also apparently does not allow chained variable declarations.
Take the id of the element you want to validate as a parameter of your function.
// validate textbox
function validate_domain(serverName){
var server = document.getElementById(serverName).value;
var domain_array = server.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(serverName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(serverName).focus();
return false;
}
}
<script type="text/javascript">
// validate textbox
function validate_domain(ele){
var nameserver = ele.value;
var domain_array = nameserver.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
ele.focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
ele.focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(document.getElementById('nameserver1')); validate_domain(document.getElementById('nameserver2')); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>
Related
My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.
There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.
trying to learn how to validate form input.
The inputs need to:
1 - Not be empty.
2 - Only contain alphabetic characters (no digits).
When I test (I've only focused on first name input field for now) it will give the correct error message if I leave it blank. But, if I but digits in the field it will submit instead of displaying error message.
What am I doing wrong?
HTML:
<form id="frm1">
<fieldset id="controls">
<div>
<label for="firstname">First Name: </label>
<input type="text" id="firstname">
<span id="errFname" class="errmsg">* You must enter a first name</span>
</div>
<div>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname">
</div>
<div>
<input type="submit" value="Submit">
</div>
</fieldset>
</form>
SCRIPT:
function checkForm(){
document.getElementById("frm1").onsubmit=function() {
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname)){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
}//close function
return false;
}//close function (checkForm)
window.onload=checkForm;
The problem is that you are returning inside each if block and that is making the whole submit callback to return.
You should create a variable and return only at the end. Something like this:
function checkForm(){
document.getElementById("frm1").addEventListener("submit", function(e) {
var errors = [];
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
errors.push("required");
}
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname) && errors.length === 0){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
errors.push("numeric");
}
//If you want, you can do something with your errors, if not, just return
//You should rethink about handling all errors here showing/hiding messages, etc.
if (errors.length > 0) {
e.preventDefault();
return false;
}
return true;
});//close function
}//close function (checkForm)
I am doing some form validation in JSP, on click on submit button "validate_access()" function is not called or not working. Sometimes this function displays a alret box and then stop doing any thing . Please tell what is wrong with this piece of code.Here is a piece of code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Data management system</title>
<script language="JavaScript" type="text/javascript">
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(document.myform1.MISDN.value=="" && document.myform1.Issue.value=="" && document.myform1.SR.value=="" && document.myform1.date.value=="")
{
alert("Manadotry fields should not left blank");
document.myform1.MISDN.focus();
document.myform1.Issue.focus();
document.myform1.SR.focus();
document.myform1.date.focus();
return false;
}
else if(!a.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.MISDN.focus();
return false;
}
else if(!(b.value.match(numbers) && b.value.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myform1.Issue.focus();
return false;
}
else if(!c.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.SR.focus();
return false;
}
else if(!d.value.match(Datee))
{
alert('Please input correct date');
document.myform1.date.focus();
return false;
}
else
return true;
}
</script>
</head>
<body>
<div class="main">
<div class="header"></div>
<div class="continer">
<div class="myform1" style="height:200px; width:300px; float:left;">
<h2>1344 Access</h2>
<form name="myform1" action="access.jsp" method="get" onsubmit="return validate_access()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>Issue:<input type="text" name="Issue" maxlength="13">
<br/>SR:<input type="text" name="SR">
<br/>Date:<input type="text" name="date" value="dd/mm/yy">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
<div class="myform2" style="float:left;height:200px; width:300px;">
<h2>O.C.S</h2>
<form name="myform2" action="ocs.jsp" method="post" onsubmit="return validate_ocs()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>SR:<input type="text" name="SR">
<br/>REASON:<input type="text" name="reason">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
</div>
</div>
</body>
Problems in your javascript are:
the first if condition check is wrong you mean || in place of &&.
then next when you call match method on empty string a error probably raise like:
Uncaught TypeError: Cannot read property 'match' of undefined
you calling .focus() continuously that doesn't making any sense, call once with a condition check.
There is something wrong in this line:var a = document.forms["myForm1"]["MISDN"].value;
Look at your source code, your form name is "myform1" not "myForm1".
JavaScript is case sensitive.
http://en.wikipedia.org/wiki/JavaScript_syntax
in your js:
document.forms["myForm1"]
but in your form(html) it is:
<form name="myform1"
Try this:
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(a == "" && b == "" && c == "" && d == "")
{ //as you have default value for d (date field), this condition will never match;
//either you can remove default value or provide different logic
alert("Manadotry fields should not left blank");
document.myForm1.MISDN.focus();
document.myForm1.Issue.focus();
document.myForm1.SR.focus();
document.myForm1.date.focus();
return false;
}
else if(a == "" && !a.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.MISDN.focus();
return false;
}
else if(!(b.match(numbers) && b.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myForm1.Issue.focus();
return false;
}
else if(!c.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.SR.focus();
return false;
}
else if(!d.match(Datee))
{
alert('Please input correct date');
document.myForm1.date.focus();
return false;
}
else
return true;
}
Your mistakes:
(i) form name spelling mistake (caseSensitive)
(ii) you used HTMLElement.value.value to check (in if conditions)
For example:
var a = document.forms["myForm1"]["MISDN"].value;
a.value.match(numbers); // it simply means HTMLElement.value.value (which will never work)
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"?
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!
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);">
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>
use the code below
if(isNaN(document.forms[0].userAge.value)){
alert('This is not a number');
}