Javascript age validation - javascript

I'm currently doing javascript validation and everything's working perfectly except my age validation. If the person enters a value of type string it must give an alert for the user to enter his/her age as a numeric value...
I'm not quite sure how to go about this so your help will be very much appreciated!
You will see what I'm trying to do in the validAge function in the if-statement: line 55
Here is my code I have so far!
<!DOCTYPE HTML>
<html>
<head>
<title>Question 1 / Vraag 1 - Basic JavaScript Validaton / Basiese JavaScript validasie
</title>
<link rel="Stylesheet" type="text/css" href="style.css" />
<script language="javascript">
function validate()
{
var firstname = document.getElementById("firstname");
var surname = document.getElementById("surname");
var age = document.getElementById("age");
var email = document.getElementById("email");
if(notEmpty(firstname, "ENTER USERNAME"))
{
if(notEmpty(surname, "ENTER SURNAME"))
{
if(notEmpty(age, "ENTER AGE"))
{
if(validAge(age, "AGE MUST BE A NUMERIC VALUE"))
{
if(notEmpty(email, "ENTER EMAIL"))
{
if(emailValid(email, "ENTER A PROPER EMAIL ADDRESS"))
{
return emailValid();
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg)
{
if(elem.value.length == 0)
{
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
function validAge(elem, helperMsg)
{
var age = elem.value;
if(age <= 0 || age > 100 || age.type == string???))
{
alert(helperMsg);
return false;
}
return true;
}
function emailValid(elem, helperMsg)
{
var atpos = elem.value.indexOf("#");
var dotpos = elem.value.lastIndexOf(".");
if(atpos < 0 || dotpos < 0)
{
alert(helperMsg);
return false;
}
return true;
}
</script>
</head>
<body>
<form method="get" action="">
<table>
<tr>
<td> Firstname:</td>
<td> <input type="text" name="firstname" id="firstname" /><span id="fnError">
</span></td>
</tr>
<tr>
<td> Surname:</td>
<td> <input type="text" name="surname" id="surname"/><span id="snError">
</span></td>
</tr>
<tr>
<td> Age:</td>
<td> <input type="text" name="age" id="age"/><span id="aError">
</span></td>
</tr>
<tr>
<td> Email:</td>
<td><input type="text" name="email" id="email"/><span id="eError">
</span></td>
</tr>
<tr><td colspan="2"><input type="button" value="Validate" onClick="validate()" /></td></tr>
</table>
</form>
</body>
</html>

Use a RegExp to check whether it's a valid age. Methods such as isNaN will still allow floating-point numbers, though I have never heard anyone saying My age is twelve dot three.:
function validAge(elem, helperMsg)
{
var age = elem.value;
//Two digits, so anything between and including 0 and 99
if(/^\d{1,2}$/,test(age))
{
alert(helperMsg);
return false;
}
return true;
}
Another tip: Instead of nesting hundreds of if-conditions, you can also use the logical && (AND) operator.
if(a){
if(b){
if(c){
...
can be shortened to:
if(a && B && c){

You can use the isNan function!

I think this is what you want:
if(isNaN(age) || age <= 0 || age > 100))
The isNaN(age) uses the isNaN[MDN] function to check whether or not age is actually a number.
Note that this will allow floating point ages, which may or may not be what you want. If you prefer, you can only allow integer ages with this condition:
age % 1 === 0
Also, I would avoid nesting all the if statements. You could do a return after each one, like this:
if(notEmpty(firstname, "ENTER USERNAME")) return false;
if(notEmpty(surname, "ENTER SURNAME")) return false;
if(notEmpty(age, "ENTER AGE")) return false;
/// skip a few ...
return emailValid();
BTW, there are some people who are over 100 years old. This app would be bad for their user experience.

Try this using isNaN():
function validAge(elem, helperMsg)
{
var age = elem.value;
// If age is Not a Number, not at least 1, greater than 100, or has a decimal place.
if(isNaN(age) || age <= 0 || age > 100 || age.indexOf(".") >= 0)
{
alert(helperMsg);
return false;
}
return true;
}

All the above answers are correct.. If you think of re-usability please have a look at this plugin. It validates a form with small effort..

<html>
<head>
<title>Name</title>
<script>
function validatetext()
{
if(document.sign.fname.value=="")
{
alert("Missing First name!");
}
if(isNaN(document.sign.age())
{
alert("Enter numaric");
}
}
</script>
</head>
<body><form method=post name="sign">
<b>name:</b>
<input name="fname" type="text" size="30" maxlength="30" />
<br>
<b>age:</b>
<input name="age" type="text" size="30" maxlength="30" />
<input type="submit" name="signup" value="sign up" onclick="validatetext();" />
</form>
</body>
</html>

Related

Validate form from an Array JavaScript

I'm new to JavaScript and i'm trying to create a login page and have the username and passwords or pins pull from an array. I tried my best to put it together and make it work, but I can't. Any help would be appertained. At the moment the login form is not pulling from the array. Please help.
original code:
}
var customer= ["John", "Mary", "Doe"]
var pin = [1452, 7858, 2016]
function validateusername(username) {
if (username == customer) {
return true;
}else {
return false;
}
}
function validatepassword(password) {
if (pin == pin) {
return true;
}else {
return false;
}
}
New updated code( still doesn't run)
<body>
<h1> Login to the Web ATM </h1>
<script src="js/scripts.js"></script>
<section class="loginform cf">
</section>
<form id="login" name="login" action="index_submit" onSubmit="return false" method="get" accept-charset="utf-8">
<table>
<tr>
<td> <label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" placeholder="UserName" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="password">PIN Number:</label></td>
<td><input type="password" name="password" id="password" placeholder="PIN" pattern="[0-9]{4}" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="email" name="email" id="email" placeholder="yourname#email.com" pattern="^(?=.*\..*)(?=.*#.*).*$" ><br/></td>
<td><div id="reqDisplay"></div></td>
</tr>
<tr>
<td> Empty </td>
<td><input id="emailBox" type="checkbox" name="checkbox" value="email transaction " onchange="displayReq()"/>email me a transaction confirmation</td>
<td> </td>
</tr>
<tr>
<td></td>
<td> Select an Account: <select>
<option value="account1">Checking</option>
<option value="account2">Savings</option>
<option value="account2">Money Market</option></select></td>
<td><input type="submit" value="Continue>>" onclick="validateForm()"></td>
</form>
</table>
<script type="text/javascript">
function displayReq(){
var divToReplace = document.getElementById("reqDisplay");
var chk = document.getElementById("emailBox");
var emailField = document.getElementById("email");
if (chk.checked) {
emailField.required = true;
divToReplace.innerHTML = "REQUIRED";
}else {
divToReplace.innerHTML = "";
emailField.required = false;
}
}
function validateForm(){
var myForm = document.getElementById("login");
var chk = document.getElementById("emailBox");
}
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
function validateemail(email) {
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
}else {
return false;
}
if (validateusername(myForm.username.value) && validatepassword(myForm.password.value) && (validateemail(myForm.email.value) || !chk.checked) ) {
alert("Welcome to your online ATM");
} else {
alert("Sorry the information you provided is incorrect");
}
}
</script>
You need to use different names for the global arrays and the function parameters. Otherwise, the parameter variables shadow the global variables, and you can't refer to the global variables inside the functions.
And the way to tell if something is in an array is with the indexOf() method, not ==.
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_username(username) {
return all_usernames.indexOf(username) > -1;
}
function validate_pin(pin) {
return all_pins.indexOf(pin) > -1;
}
Note that having separate functions to validate the username and PIN will not tell you if the user entered their correct PIN. For instance, if they enter username John, it won't check if they entered PIN 1452, it will allow 2016 or 7858 as well. You should use a single function to valdate both:
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
}

Checking if integer JavaScript forms

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

Can two or more conditional statements placed inside a function in javascript?

I am newbie in JavaScript. Can't find answer for this. I am not sure whether it is relevant.
I have a registration form with 2 fields.On submit, it should be validated. Here in my code, first written if condition only works. If the first if statement is commented, second if condition works.
HTML CODE :
<body>
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
</body>
JS:
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
In JSFiddle, it gives a error like
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x56b3ed0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x5c03510>, 'help_text': '', 'name': 'js_wrap'}"}
I donno what this error means!
You have to rewrite your validation code a bit.
Check demo - Demo:
Your problems:
function returns before gender is checked;
you cannot check multiple checkboxes this way: if(gender.checked)
Below is the working code
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form();">Submit</button>
</form>
</div>
When the function hits a return line, it leaves (ie returns from) the function and doesn't execute anything else in that function.
What people usually do is have a variable called valid or something similar that defaults to true. Then they have if statements that check only for things that would make the form invalid. If one of those if statements gets tripped, it handles the issue (eg telling the user that they need to fill in their gender) and sets valid to false. At the end, and only at the end, it returns valid. This way, if anything is making the form invalid, the function will return invalid, but nothing bad will happen if more than one if statement gets tripped because you can set valid to be false as many times as you want without causing any issues.
You can do it in this way.
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
var boolValidateName = validateName(name);
var boolValidateGnder = validateGnder(name);
if(boolValidateName && boolValidateGnder){
//if both are validate
}else{
//if either of or both not validate
}
}
var validateName = function (name){
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
}
var validateGender = function(gender){
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
Your return statement is not placed very well.
You can break your business login into function and call it.So,every return statement get an equal chance to run.
getElementsByName will return nodelist. You will have to iterate it to get the checked value.
Also note, return ends the current function and returns execution flow to the calling function hence any line of code after execution of return will not be executed.
Do not forget to empty('') the error messages.
Try this:
function validate_form() {
var name = document.getElementById("id1").value;
var gender = document.getElementsByName("gender");
document.getElementById("label1").innerHTML = '';
document.getElementById("label2").innerHTML = '';
var genValue = '';
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genValue = gender[i].value;
}
}
if (!name) {
document.getElementById("label1").innerHTML = "Enter Name";
return false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
return false;
} else if (!genValue) {
document.getElementById("label2").innerHTML = "Check gender";
return false;
}
return true;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td>
<label>Enter Full Name :</label>
</td>
<td>
<input type="text" id="id1" name="username" placeholder="minimum 6 charactors">
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label1"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female">
<label>Female</label>
<input type="radio" name="gender" value="male">
<label>Male</label>
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label2"></label>
</td>
</tr>
</table>
<br/>
<button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
Fiddle here
When your first block of if..else statements returns, it returns for the whole function and the if for gender never even runs. remove:
else
{
return true;
}

JavaScript-form validation

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)

clarification on validating a textbox

I have totally 6 textboxes here and i have applied different validations for them but none of them are working. here is my code can someone help me out where i have gone wrong.
Each textbox have different condition
1)it should accept only alphabets
2)it should accept only numbers
3)it should accept only email
4)it should accept only alphabets if u enter anything other then alphabet and press submit button background color of that particular textbox will change
<!DOCTYPE>
<html>
<head>
<title> Text Boxes </title>
<script>
function test(){
if(form.alphabets.value == "") {
alert('Please enter name');
return false;
} else {
if (!form.alphabets.value.match(/^[a-zA-Z]+$/)) {
alert("Please Enter only alphabets");
return false;
}
}
if(form.numbers.value == "") {
alert('Please enter phone number ');
return false;
} else {
if (!form.numbers.value.match(/^[0-9]+$/)) {
form.numbers.value="";
form.numbers.focus();
alert("Please Enter only numbers");
return false;
}
}
if(form.email.value == "") {
alert('Please enter email ');
return false;
} else {
if (!form.email.value.match(/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/) ) {
form.email.value="";
alert("Please Enter Valid email address");
form.email.focus();
return false;
}
}
if(form.alphabets1.value == "") {
alert('Please don't enter numbers ');
return false;
} else {
if (!form.alphabets1.value.match(/^[a-zA-Z]+$/)) {
form.alphabets1.value="";
form.alphabets1.focus();
form.alphabets1.style.background="Red";
alert("Please Enter only alphabets");
return false;
}
}
function check()
{
var text = document.getElementById("txtarea_content").value;
if(text.length >= 4)
{
alert('Length should not be greater than 4');
return false;
}
else
{
return true;
}
}
function sum()
{
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
document.getElementById('txt3').value = result;
}
</script>
</head>
<body>
<form name="form" method ="post">
<table>
<tr>
<td>Enter only Alphabets :</td>
<td><input type="text" name="alphabets" /></td>
</tr>
<tr>
<td>Enter only Numbers :</td>
<td><input type="text" name="numbers" /></td>
</tr>
<tr>
<td>Enter your Email Address : </td>
<td><input type="text" name="email"> </td>
</tr>
<tr>
<td>Enter only alphabets</td>
<td><input type="text" name="alphabets1"</td>
</tr>
<td> </td>
</table>
<button onclick="test();"> click me </button>
<td><br></td>
<td></br></td>
<div>
Enter only 4 values : <input type="text" length="3" id="txtarea_content" onkeypress="return check();"> </textarea>
</div>
<tr>
<td>Enter Two Numbers : <input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
</td>
<td> Result :<input type="text" id="txt3" /></td>
</tr>
</form>
</body>
</html>
You copy code error you function test() mistake } and alert('Please don't enter numbers ') error ' in don't .Please correct the code!
Hope this help!
why not try to get their id instead..here is the code
var alpa = document.getElementById('alphabets');
if(alpa.value == "") {
alert('Please enter name');
return;
} else {
if (!alpa.value.match(/^[a-zA-Z]+$/)) {
alert("Please Enter only alphabets");
return;
}
}
hope this'll help
The problem is here. Single quote(') ends unnecessary in the middle. Use double quotes(") in that place.
Instead of this
if(form.alphabets1.value == "") {
alert('Please don't enter numbers ');
return false;
}
Use this
if(form.alphabets1.value == "") {
alert("Please don't enter numbers ");
return false;
}
As tuan huynh said, you forgot to close the function test statement with }. In addition, have you think that some people would end up entering spaces in the name - because they have two names, for example? This regexp would accept those spaces (keep in mind that \w is the same than a-zA-Z ):
/^[\w|\s]+$/
People may even want to put accents on vowels or similar symbols in their names, and they won't match with a regexp that only looks for alphabets. This would make it, at least, for accents:
/^[\w|\s|á-úÁ-Ú|à-ùÀ-Ù]+$/
I hope this helps.

Categories