/    Sign up×
Community /Pin to ProfileBookmark

JS code not working

Hi
I want to create a javascript form validation but i cant validate with the following code.
What is wrong with the code? How to create a form validation without much modification of the following code-

[CODE]<html>
<head><title>Javascript Validation</title>
<style>
.lf{
position:relative;
left: 30px;
float right;
}
</style>
<script>
function validate()
{
var c=document.getElementById(“f1″).value;
if(c.length<1)
alert(” Name Field can’t be blank”);
if(c.length<=5)
alert(“Enter a valid name”);
var a=parseInt(document.getElementById(“f6”).value);alert(a);
var b=document.getElementById(“f7”).value;alert(b);
var d=document.getElementById(“f8″).value;alert(d);
var lp=0;
if((d%400)==0 && (d%100==0) || (d%4==0))
lp=1;
if((a==31) && ((b==”4″) || (b==”6″) || (b==”9″) || (b==”11”)) )
alert(“Date out of Range”);
if((lp==0) && ((a==”29″) || (b==”2″) )
alert(“Date out of Range”);
}
</script>
</head>
<body>
<div style=”width:50%;background-color:lightgray;”>
<fieldset>
<legend style=”color:brown;font-weight:bold;”> SignUp Form</legend>
<table height=300>
<form>
<tr><td> FirstName:&nbsp;&nbsp;<input type=”text” name=”fn” id=”f1″ class=”lf” size=50 /></td></tr>
<tr><td> Address: &nbsp;&nbsp;&nbsp; <input type=”text” name=”adr” id=”f2″ class=”lf” size=50 /></td></tr><br/><br/>
<tr><td> Zip:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type=”text” name=”zp” id=”f3″ class=”lf” size=20 /></td></tr><br/><br/>
<tr><td> UserName:&nbsp;<input type=”text” name=”fn” id=”f4″ class=”lf” size=30 /></td></tr>
<tr><td> Password: &nbsp;&nbsp;<input type=”password” name=”fn” id=”f5″ class=”lf” size=30 /></td></tr>
<tr><td> DOB: <br /><br />Day:&nbsp;&nbsp;&nbsp;<input type=”text” name=”dy” id=”f6″ />
Month:&nbsp;<input type=”text” name=”m1″ id=”f7″ />
Year:&nbsp;<input type=”text” name=”m2″ id=”f8″ /></td></tr>
<tr><td> Email:&nbsp;&nbsp;
<input type=”text” name=”fn” id=”f9″ size=50 /></td></tr>
<tr><td><center>
<input type=”submit” value=”submit” onClick=”validate()” />
</center></td></tr>
</form>
</table>
</fieldset></div></body>
</html>[/CODE]

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@007JulienNov 19.2011 — The function validate and the onclick event has to return boolean values. Then you have to write, for example, in the function
[CODE]if(c.length<1) {alert(" Name Field can't be blank");return false;}
if(c.length<=5) {alert("Enter a valid name");return false;}
// ...
// At the end if all values are right.
return true;
[/CODE]

and
[code=html]<input type="submit" value="submit" onclick="return validate()" /> [/code]
Then the click submit or not the form...
Copy linkTweet thisAlerts:
@jitcauthorNov 19.2011 — Hi 007Julien,

Thanks for the reply.I tried to use your code but the code is still not working.

I post here the modified code for your convenience-
[CODE]
<html>
<head><title>Javascript Validation</title>
<style>
.lf{
position:relative;
left: 30px;
float right;
}
</style>
<script>
function validate()
{
var c=document.getElementById("f1").value;

if(c.length<1){
alert(" Name Field can't be blank");
return false;}

if(c.length<=5){
alert("Enter a valid name");
return false;
}

var a=parseInt(document.getElementById("f6").value);
alert(a);
var b=document.getElementById("f7").value;
var d=document.getElementById("f8").value;
var lp=0;
if(((d%400)==0) && (d%100==0) || (d%4==0))
lp=1;
if((a==31) && ((b=="4") || (b=="6") || (b=="9") || (b=="11") ) {
alert("Date out of Range");
return false;}
if((lp==0) && ((a=="29") || (b=="2") ) {
alert("Date out of Range");
return false;}
return true;
}
</script>
</head>
<body>
<div style="width:50%;background-color:lightgray;">
<fieldset>

<legend style="color:brown;font-weight:bold;"> SignUp Form</legend>
<table height=300>

<form>
<tr><td> FirstName:&nbsp;&nbsp;<input type="text" name="fn" id="f1" class="lf" size=50 /></td></tr>
<tr><td> Address: &nbsp;&nbsp;&nbsp; <input type="text" name="adr" id="f2" class="lf" size=50 /></td></tr><br/><br/>
<tr><td> Zip:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="zp" id="f3" class="lf" size=20 /></td></tr><br/><br/>
<tr><td> UserName:&nbsp;<input type="text" name="fn" id="f4" class="lf" size=30 /></td></tr>
<tr><td> Password: &nbsp;&nbsp;<input type="password" name="fn" id="f5" class="lf" size=30 /></td></tr>
<tr><td> DOB: <br /><br />Day:&nbsp;&nbsp;&nbsp;<input type="text" name="dy" id="f6" />
Month:&nbsp;<input type="text" name="m1" id="f7" />
Year:&nbsp;<input type="text" name="m2" id="f8" /></td></tr>
<tr><td> Email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="fn" id="f9" size=50 /></td></tr>
<tr><td><center>

<input type="submit" value="submit" onClick="return validate()" />
</center></td></tr>
</form>

</table>


</fieldset></div></body>
</html>


[/CODE]
Copy linkTweet thisAlerts:
@007JulienNov 19.2011 — We make always errors... Use a debugger like Firebug for Mozilla FireFox or other development consoles (double click on the status bar in IE and see the source code for the line...etc.); I find two errors with Firebug

[CODE]if((a==31) && ((b=="4") || (b=="6") || (b=="9") || (b=="11"))[COLOR="Red"])[/COLOR] {
alert("Date out of Range"); return false;}
if((lp==0) && ((a=="29") || (b=="2") )[COLOR="Red"])[/COLOR] {
alert("Date out of Range");
return false;}[/CODE]

Good luck !
Copy linkTweet thisAlerts:
@jitcauthorNov 20.2011 — Ok Thanks very much .It worked after making required changes.

This is the corrected code.

Can you help any further?I am trying to check the "Firstname" field with functions "isAlphabet" & "isAlphanumeric". Problem is I am not getting the "Successfully submitted" at the end proving the program is not executing the rest part!!

What can be the error in the code now?
[CODE]<html>
<head><title>Javascript Form Validation</title>
<style>
.lf{
position:relative;
left: 30px;
float right;
}
</style>
<script>
function validate()
{
var c=document.getElementById("f1").value;

if(c.length<1){
alert(" Name Field can't be blank");
return false;}

if(c.length<=5){
alert("Enter a valid name");
return false;
}

var firstname = document.getElementById('f1');
var addr = document.getElementById('f2');
if(isAlphabet(firstname, "Please enter only letters for your name"))
return true;
else
return false;

if(isAlphanumeric(addr, "Please enter only Numbers and Letters for Address"))
return true;
else
return false;


function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}
else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}
else{
alert(helperMsg);
elem.focus();
return false;
}
}

[COLOR="DarkOrange"]var dd=document.getElementById("f6").value;
var mm=document.getElementById("f7").value;
[/COLOR]
var d=parseInt(document.getElementById("f6").value);
var m=parseInt(document.getElementById("f7").value);
var y=parseInt(document.getElementById("f8").value);
var lp;
if(dd.length<1)
{
alert("Enter a date :");
return false;
}
if(mm.length<1)
{
alert("Enter a month :");
return false;
}

if((((y%400)==0) && ((y%100)==0)) || ((y%4)==0)){
lp=1;
}
else
{
lp=0;
}

if((d=="31") && ((m=="4") || (m=="6") || (m=="9") || (m=="11") ) ) {
alert("Date out of Range");
return false;}
if((lp=="0") && ((d=="29") || (m=="2") ) ) {
alert("Date out of Range");
return false;}
alert("Successfuly submitted");
return true;
}
</script>
</head>
<body>
<div style="width:50%;background-color:lightgray;">
<fieldset>

<legend style="color:brown;font-weight:bold;"> SignUp Form</legend>
<table height=300>

<form>
<tr><td> FirstName:&nbsp;&nbsp;<input type="text" name="fn" id="f1" class="lf" size=50 /></td></tr>
<tr><td> Address: &nbsp;&nbsp;&nbsp; <input type="text" name="adr" id="f2" class="lf" size=50 /></td></tr><br/><br/>
<tr><td> Zip:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="zp" id="f3" class="lf" size=20 /></td></tr><br/><br/>
<tr><td> UserName:&nbsp;<input type="text" name="fn" id="f4" class="lf" size=30 /></td></tr>
<tr><td> Password: &nbsp;&nbsp;<input type="password" name="pw" id="f5" class="lf" size=30 /></td></tr>
<tr><td> DOB: <br /><br />Day:&nbsp;&nbsp;&nbsp;<input type="text" name="dy" id="f6" />
Month:&nbsp;<input type="text" name="mth" id="f7" />
Year:&nbsp;<input type="text" name="yr" id="f8" /></td></tr>
<tr><td> Email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="fn" id="f9" size=50 /></td></tr>
<tr><td><center>

<input type="submit" value="submit" onclick="return validate()" />
</center></td></tr>
</form>

</table>


</fieldset></div></body>
</html>

[/CODE]

Please help.
Copy linkTweet thisAlerts:
@JunkMaleNov 20.2011 — To get a reliable Leap Year check, use the following.

[CODE]leapYear = ( new Date(new Date().getFullYear(),1,29).getMonth()<2 );[/CODE]

The logic is worked out by the operating system providing the correct time information to Javascript in the first place but the way this works is it evaluates the 29th of feb date in this current year and returns the appropriate month.

If were in a leap year then 29th Feb exists and month == 1 match otherwise month =2 which is March as 29th Feb in a non-leap year evaluates to 1st March.

So leapYear will either be True or False.

This can be adapted to a simple function like
[CODE]function leapYearIn(year){
// we will assume that this value passed is a number
return ( new Date(year,1,29).getMonth()<2 );
}[/CODE]


So passing any year will return the appropriate value as the [CODE](d%400)==0) && (d%100==0) || (d%4==0)[/CODE] does not evaluate properly, this much can be found online if you search. I remember getting taught a lesson on a website as to exactly why and it appears that the calendar drops a leapyear every so often, can not remember how often but the example code, as rough as it is demonstrates this point, each "*" is a 4 year leap year and this will only output a sentence if the leap was larger than 4 years. You then get a sentence when the drop leap year is detected

[code=html]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
<!--

function leapYearIn(year){
// we will assume that this value passed is a number
return ( new Date(year,1,29).getMonth()<2 );
}


leapDiff = 0;
lastLeap = 0;
for(yr=1000; yr<3000; yr++)
if( leapYearIn(yr) ){
leapDiff = yr - lastLeap;
if( leapDiff >4 || leapDiff <4 ){ document.write("<br />Last Leap year was ",leapDiff,"Years ago. This year is (",yr,") a leap year.<br />");
}else{ document.write("*");}
lastLeap = yr;
}
//-->
</script>
</head>

<body>
</body>
</html>[/code]


Which you will see over time you have differing periods between leap years and dropped leap years.

So the only truly accurate method of doing this is to have Javascript perform the calculation rather than rely on the unreliable text book method.

The OutputLast Leap year was 1004Years ago. This year is (1004) a leap year.

***********************
Last Leap year was 8Years ago. This year is (1104) a leap year.

************************************************
Last Leap year was 8Years ago. This year is (1304) a leap year.

***********************
Last Leap year was 8Years ago. This year is (1404) a leap year.

***********************
Last Leap year was 8Years ago. This year is (1504) a leap year.

************************************************
Last Leap year was 8Years ago. This year is (1704) a leap year.

***********************
Last Leap year was 8Years ago. This year is (1804) a leap year.

***********************
Last Leap year was 8Years ago. This year is (1904) a leap year.

************************************************
Last Leap year was 8Years ago. This year is (2104) a leap year.

***********************
Last Leap year was 8Years ago. This year is (2204) a leap year.

***********************
Last Leap year was 8Years ago. This year is (2304) a leap year.

************************************************
Last Leap year was 8Years ago. This year is (2504) a leap year.

***********************
Last Leap year was 8Years ago. This year is (2604) a leap year.

***********************
Last Leap year was 8Years ago. This year is (2704) a leap year.

************************************************
Last Leap year was 8Years ago. This year is (2904) a leap year.

***********************[/QUOTE]
remember, each [B]*[/B] represents 4 years. I removed the output and chose a character to highlight the difference and also shows up that some periods are shorter than others.

Think its two 808 to every 1616 year frequencies as a ratio.

A more visual-sih output

[code=html]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
<!--

function leapYearIn(year){
// we will assume that this value passed is a number
return ( new Date(year,1,29).getMonth()<2 );
}


// a leap year, JS feb == month 1 as Jan is month 0, therefore 29th Feb in any non leap year is 1st March or Month 2
leapYear = ( new Date(new Date().getFullYear(),1,29).getMonth()<2 );
//document.write("Leap Year This Year? : ",leapYear,"<br />");
leapDiff = 0;
lastLeap = 0;
for(yr=1000; yr<3000; yr++)
if( leapYearIn(yr) ){
leapDiff = yr - lastLeap;
if( leapDiff >4 || leapDiff <4 ){
document.write("<br />$");
}else{ document.write("*");}
lastLeap = yr;
}
//-->
</script>
</head>

<body>
</body>
</html>
[/code]


The Output$***********************

$*
**
*********************************************

$*
**
********************

$*
**
********************

$*
**
*********************************************

$*
**
********************

$*
**
********************

$*
**
*********************************************

$*
**
********************

$*
**
********************

$*
**
*********************************************

$*
**
********************

$*
**
********************

$*
**
*********************************************

$*
**
********************[/QUOTE]


$ = Drop Leap Year

*
= Leap Year

Remove the <br /> from the document.write that outputs the $ sign to get a long string
Copy linkTweet thisAlerts:
@Azzdog_devNov 20.2011 — Five seconds into reading the code, I saw one of the errors (didn't read the whole thing)

You opened the script tag like this <script>. Try using <script type="text/JavaScript">

You need to tell it what language the script is using. Some browsers may be able to figure this out, usually you have to say what it is. Also, some browsers do not execute JavaScript as efficiently as others. For example:

I wrote a JavaScript that hides and shows div tags in an animated fashion. I saved it to USB. I opened the site in Mozilla Firefox on a Linux based os. Didn't work. I removed it and inserted it into a windows xp machine, and tested it with ie and chrome. Both work. I know I used two different os, it doesn't matter. It worked in one condition, not the other. Even if you do fix the code so it does work (technically) but doesn't work properly, try different browser. And if your not using windows, try a windows pc. I don't use my laptop for web devlopment because js doesn't work properly
Copy linkTweet thisAlerts:
@jitcauthorNov 20.2011 — Not an answer @Junmale :mad:

nice joke
Copy linkTweet thisAlerts:
@007JulienNov 20.2011 — Can the O'Connors or O&#8217;connors or &#201;douard-Marie or Julien de Prab&#232;re join your site ? Make simple tests ! Especially in Javascript...

A simple method to validate the date :
[CODE]dt=new Date(year,month,day);
if (dt.getFullyear()!=year || dt.getMonth()!=month||dt.getDate!=day) {alert("Date out of Range");}[/CODE]


But it's really boring to serve a form, when Javascript allows to choose a date with a simple click like on this page (sorry for the French version)...

NB : Your page has no DOCTYPE and no meta tag with charset.
×

Success!

Help @jitc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...