/    Sign up×
Community /Pin to ProfileBookmark

Help with forms

I am trying to create a web page containing a from, this form should contain the following input fields: full name (a text field) and date of birth (another text field, with input required in the form DD/MM/YYYY.

Each text field should have suitable labels to identify what is required to be input within them. The contents of each text field should check on a blur event to ensure they are not empty. Once both text fields have suitable contents they should perform checks on contents as follows:

1)the full name text field contents should start with a letter, contain at least one space, and end with a letter
2)the first and second characters of the date of birth text field should be digits, as the forth and fifth characters, and seventh, eight, ninth and tenths characters.

If the contents of a field, or both fields, does not match the requirements above the user should be able to clear both contents of both and display a suitable error message in a alert box.

If the contents are validated, the form should display an alert box with the following message: “Hellow <initial(s)><Surname>. Did you know that your next birthday you will be <age> years old?”.

Example if the user inputs “Tony Charles Lynton Blair” in the name field and “06/05/1953” in the field date the resulting output should be (if the current date is the 17/01/2004:

[B]Hello T.C.L. Blair. Did you know that on your next birthday you will be 52 years old?[/B]

I dont know if any body can help as I’m new to Javascript and end up in knots trying to work out how to do this script.

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@CharlesJul 17.2004 — [font=georgia]Such a particular set of requirements is a sure and certain indication of a homework assignment. You are, however, welcome to ask questions about particular parts of the task, but you are going to have to put everything together yourself.

And be warned, my answers are calculated to make it very clear that no beginner wrote them.[/font]
Copy linkTweet thisAlerts:
@steelersfan88Jul 17.2004 — Definately as Charles said. And the instructions are bad as well. One should not validate on the when the onBlur event is triggered. Why not?

> One could have pressed the TAB key accidentally

> One might need to gain information to complete a field, and completes other fields first

> One might choose to complete to form in a different order, so that it is required to toggle between fields

> One may accidentally click into another field

> etc ...


Names should not be checked just to make sure they are in the form of: A134B A3624.#$&?F. That is not a name. More along the lines of a regular expression, such as [font=monospace]/(s*[A-Za-z]+s*){2,}/[/font], assuming a name could be any amount of names (such as John Anthony Mark Joe Matt Mike Johnson).

The date would also be checked in this fashion, such as with [font=monospace]/d{2}/d{2}/d{4}/[/font]. You should know how to do it from here, assuming Charles is right.

I won't even get into the display, but it would be simply require matching the word boundaries. This could be done using the [font=monospace]exec[/font] method of a regular expression. Then you'd have to make a new date from the current date and the birthdate. From this date, you'd extract the number of years, and add 1 if a decimal exists.

I tried to live up to Charles "no beginner" clause, so I'll let you try to figure out to put them together, again, assuming Charles is right in his assumption.

Dr. Script

Dr. Script
Copy linkTweet thisAlerts:
@KidCreationJul 17.2004 — i think they're trying to tell you not to over complicate it the form with pointless functions just to prove that you can do them, even if this isnt what they're saying then it's still a good point to bear in mind, if you overcomplicate something you're only giving more ways for it to go wrong.

good luck

p.s a submit button is a far better idea than it auto submiting
Copy linkTweet thisAlerts:
@steelersfan88Jul 17.2004 — Not exactly what we are saying, but you could interpret similarly.

We say, "If it's homework, its your work, not ours."

We (maybe I) would say, "If it's not homework, it's pointless"

Can we have the confirmation that it is homework or not?
Copy linkTweet thisAlerts:
@tara21authorJul 17.2004 — Its home work unfortunatly and Ive managed to get this far:

<HTML>

<TITLE>Test Input Validation</TITLE>

<script Language="JavaScript">

function example(form)

{

var result = false;

var theStr = new String(form);

var index = theStr.indexOf("");

if (index > 0)

{

var pindex = theStr.indexOf(".",index);

if ((pindex > index+1) && (theStr.length > pindex+1))

result = true;

}

return result;

}

function validRequired(formField,fieldLabel)

{

var result = true;

if (formField.value == "")
{
alert('Please enter a value for the "' + fieldLabel +'" field.');
formField.focus();
result = false;

}

return result;

}

function allDigits(str)

{

return inValidCharSet(str,"0123456789");

}

function inValidCharSet(str,charset)

{

var result = true;


for (var i=0;i<str.length;i++)
if (charset.indexOf(str.substr(i,1))<0)
{
result = false;
break;
}

return result;

}

function validNum(formField,fieldLabel,required)

{

var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result)
{
if (!allDigits(formField.value))
{
alert('Please enter a number for the "' + fieldLabel +'" field.');
formField.focus();
result = false;
}
}

return result;

}

function validDate(formField,fieldLabel,required)

{

var result = true;

if (required && !validRequired(formField,fieldLabel))
result = false;

if (result)
{
var elems = formField.value.split("/");

result = (elems.length == 3); // should be three components

if (result)
{
var month = parseInt(elems[0],10);
var day = parseInt(elems[1],10);
var year = parseInt(elems[2],10);
result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
allDigits(elems[1]) && (day > 0) && (day < 32) &&
allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
}

if (!result)
{
alert('Please enter a date in the format MM/DD/YYYY for the "' + fieldLabel +'" field.');
formField.focus();
}
}

return result;

}

function validateForm(theForm)

{

if (!validRequired(theForm.fullname,"Name"))
return false;

if (!validDate(theForm.available,"Date Available",true))
return false;

return true;


}

</script>

</HEAD>

<BODY>

<form name="theform">

<p>Name: <input name="fullname" onBlur="required(this.value) size="32" ><br>

Date Available: <input name="available" size="16" >(dd/mm/yyyy)<br>

<INPUT TYPE="button" NAME="button" Value="Click" onClick="validateForm(theform)" >

<input type="reset" name="reset">

</form>

</BODY>

</HTML>

But now I'm lost, I can not manage to get the alert box to open with the answer require, as explained in the first post, I'm sure javascript is stright forward and I'm making it alot more difficult then it is. ive trid to addindexOf() and last IndexOf() to obtain the require alterations to the name and charAt() for the date but all I recieve is errors.

What am I doing wrong?
Copy linkTweet thisAlerts:
@steelersfan88Jul 17.2004 — The point is, we here do not care how a teacher or whoever wnats it done. We give the best way. One can validate a name and date as I showed above, with regular expressions. If both turn out to be tested true, you then would make a new Date from the entered date and the current date. You would then take the milliseconds and divide it to reuslt in years.

Dr. Script
Copy linkTweet thisAlerts:
@KidCreationJul 17.2004 — hey listen if its homework then at the end of the day you should know how to do it, if your stuck just ask your teacher, if they havent taught you how to do it then they can't expect you to just do it, jus show em how far you've got. you'll be happier at the end if you do it yourself, and don't say i don't know cos i do, i'm a student too

good luck and don't worry
Copy linkTweet thisAlerts:
@tara21authorJul 18.2004 — The homework is for work, being a woman I wasn't going to let the twats at work get the better of me, unforntunatly my big mounth has got me into this trouble.

I have tried all afternoon without much success I just cant seem to get my head round were to place addindexOf(), last IndexOf() and charAt() in the script to enable it to work the way it should.
Copy linkTweet thisAlerts:
@PittimannJul 18.2004 — Hi!

Not really tested, but should do a part of what you need:[code=php]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script language="JavaScript" type="text/javascript">
<!--
function check(){
var monthDays=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var msg='';
var foc=null;
var nowDate=new Date();
nameVal=document.forms[0].fullName.value;
dateVal=document.forms[0].dateOfBirth.value;
if(nameVal.indexOf(' ')<1||!testChar(nameVal.substring(0,1),0)||!testChar(nameVal.substring(nameVal.length-1,nameVal.length),0)){//check if name entered has correct format
msg+='Invalid entry in the name field!n';
foc=document.forms[0].fullName;
}
if(!testChar(dateVal,1)){//check if date entered has correct format
msg+='Invalid entry in the date field!n';
foc=document.forms[0].dateOfBirth;
}
if(testChar(dateVal,1)){
splitDate=dateVal.split('/');
year=splitDate[2];
month=splitDate[1]-1;
day=splitDate[0];
testDate=new Date(year,month,day);
if(nowDate-testDate<=0){//check if date entered is in the past
msg+='It seems you have not been born yet!n';
foc=document.forms[0].dateOfBirth;
}
if ((year%4==0&&year%100!=0)||(year%100==0&&year%400==0)) monthDays[1]=29;
else monthDays[1]=28;
if(month>11||day>monthDays[month]){//check if date entered exists
msg+='The date '+day+'/'+(month+1)+'/'+year+' does not exist!n'
foc=document.forms[0].dateOfBirth;
}
}
if(msg==""){
diff=nowDate-testDate
yearcount=0;
if((nowDate.getMonth()<testDate.getMonth())||(nowDate.getMonth()==testDate.getMonth()&&nowDate.getDate()<testDate.getDate())){
yearcount=-1;
}
while(nowDate.getFullYear()>=testDate.getFullYear()){
nowDate.setYear(nowDate.getFullYear()-1);
yearcount++;//calculate age in years
}
var today;
if(nowDate.getMonth()==testDate.getMonth()&&nowDate.getDate()==testDate.getDate()){//check if birthday is today
today=true;
}
nameSplit=nameVal.split(' ');
dispName='';
for (var i=0;i<nameSplit.length;i++){
if(i<nameSplit.length-1){
dispName+=nameSplit[i].substring(0,1)+'. ';//initials with period
}
}
dispName+=nameSplit[nameSplit.length-1];//add last name
if(today==true)bMsg='. Congratulations! Today is your '+(yearcount-1)+stNdRdTh((yearcount-1))+' birthday!';//message if birthday is today
else bMsg='. Did you know that on your next birthday you will be '+yearcount+' years old?';//message if birthday is not today
msg='Hello '+dispName+bMsg;//concatenate 'Hello ' + initials + lastname + full stop + message
}
alert(msg);//alert error message or greeting with birthday message.
if(foc)foc.focus();//set focus to a field where error occured
}
function stNdRdTh(val){//function to add 'th', 'st', 'nd' or 'rd' to birthday
if (val!=11&&val!=12&&val!=13){
val=val.toString();
val=val.substring(val.length-1,val.length);
if (val=='1')insStNdRdTh='st';
else if (val=='2')insStNdRdTh='nd';
else if (val=='3')insStNdRdTh='rd';
else insStNdRdTh='th';
}
else insStNdRdTh='th';
return insStNdRdTh;
}
function testChar(str,val){//function to check name entry for alpha characters and date entry for correct format
if(val==0)rg=/[A-Za-z]/;
if(val==1)rg=/^(d{2})/(d{2})/(d{4})$/;
testR=rg.test(str);
return testR;
}
//-->
</script>
</head>
<body>
<form>
<span style="position:absolute;top:10px">Please enter your full name: <input name="fullName" onblur="check()" value="Tony Charles Lynton Blair" style="position:absolute;left:420px" size=30></span>
<span style="position:absolute;top:40px">Please enter your date of birth (DD/MM/YYYY): <input name="dateOfBirth" onblur="check()" value="06/05/1953" style="position:absolute;left:420px"></span>
<span style="position:absolute;top:70px"><input type="button" value="click" onclick="check()" style="position:absolute;left: 420px"></span>
</form>
</body>
</html>[/code]
Hope, it helps.

Cheers - Pit
Copy linkTweet thisAlerts:
@tara21authorJul 18.2004 — Thank I will try it now, if there is a problem how do I check for errors or is it a case of seach ans hope
×

Success!

Help @tara21 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 6.17,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...