Welcome to WebmasterWorld Guest from 54.166.33.25

Forum Moderators: open

JavaScript for required form fields and validation

   
6:20 pm on Sep 9, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Can anyone tell me the javascript to ensure required fields in a form and some basic validation e.g.

Required fields:
Name, Email, Phone, Address, Date1, Date2

Validation:
- Email should contain an @
- Errrm what else?

6:32 pm on Sep 9, 2002 (gmt 0)

WebmasterWorld Senior Member rcjordan is a WebmasterWorld Top Contributor of All Time 10+ Year Member


http://www.w3schools.com/js/js_form.asp

http://javascript.internet.com/forms/val-date.html

Caution! JS forms validating can get code-heavy when you consider the needs of various form elements.

<added>
The most complete forms-validating js I've used:
http://developer.netscape.com/docs/examples/javascript/formval/overview.html

6:43 pm on Sep 9, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Also, you might consider using an external javascript file to hold your validation. That way if the form is used more than once, or you have mor than one form to validate, the external file is downloaded once and stored in cache instead of being downloaded each time the main page is called.
6:48 pm on Sep 9, 2002 (gmt 0)

WebmasterWorld Senior Member nick_w is a WebmasterWorld Top Contributor of All Time 10+ Year Member


Not a JS guy as you know but, I noticed this article this morning on SitePoint:
[url]http://www.webmasterbase.com/article/862[/url]

Hope it help ;-)

Nick

8:06 pm on Sep 9, 2002 (gmt 0)

10+ Year Member



Don't rely on JavaScript validation. Many errors will still get through, and some people have JavaScript turned off. Think of it as an extra service for those with JavaScript turned on, a way to cut down on the overheads involved in submitting a form and waiting for a server-generated reponse.

What do you need to validate for? Well, I can think of a few besides "e-mail must contain @":

> Phone number must contain only digits, spaces, possibly hyphens, parentheses, periods and slashes (which some people use);

> Dates must be in a recognized format (will your script be able to tell if a user has input a date in MM/DD/YY, DD/MM/YY, YY/MM/DD? What about a date like 01/02/03?);

> Some intelligent processing is required. If you're required users to enter dates in MM/DD/YY format and they type "12-9-2002" it might be more helpful to convert it to "12/09/02" than to say "Date not in a valid format" or something equally opaque and, for the average user, terrifying.

> Should the dates be in a particular order? For example, should Date1 always be earlier than Date2 (you might be thinking of a return rail ticket, for example)? I think JavaScript can check for that, too, although the code might start getting a bit complicated (PHP, for example, can do this far more efficiently).

8:16 pm on Sep 9, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Golly, there is lots to validate if you really want to.

No special characters in a name field
5 or 9 digits for zip code
6 chars for postal code
blank fields where there shouldn't be
check to see if a button is selected before submitting

the list is endless. Any form element can be validated several ways.

name too long
name too short

credit card 15 or 16 digits

etc. etc.

1:30 am on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



5 or 9 digits for zip code
6 chars for postal code

Er, we use 4 digit post codes where I live. Some things are best left free-form.

9:28 am on Sep 10, 2002 (gmt 0)

10+ Year Member



British Postal Codes:
One or two letters; followed by either: one digit, two digits, or one digit and one letter; a space; one digit; two letters.

German Postal Codes:
Five digits, not including optional "D-" prefix.

Swiss Postal Codes:
Four digits, not including optional "CH-" prefix.

Canadian Postal Codes:
Letter, digit, letter, space, digit, letter, digit.

That's always assuming you can actually find the postal code. You may have put in several text input fields for various parts of the address, but different countries have different ways of organizing postal addresses. If you've used a single text area, validating addresses can be herculean task:

UK addresses:
Fred Smith,
Sales Dept.,
Widgits plc,
8, Somesuch Street,
Anytown,
AA99 9ZZ

German addresses:
Widgits GmbH,
-- Verkaufsabteilung --
z.Hd. Frederick Schmidt,
Irgendeine Straße 8,
99999 Musterstadt

(So, in Germany, it's: Company - department - recipient - street name and house number - postal code and city name. Any other format will be sent back "address incomplete", trust me on this.)

Better not to attempt to validate addresses, but to provide a confirmation page, giving the user a chance to correct any errors. If he has, say, ordered something and provided his credit card details, it's in his own interest to provide a correct address.

10:30 am on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member


WOW!
Some very helpful points, thankyou.
I will stick to basic validation as the majority of problems come from people not entering a phone number, email address... If I get toooo specific it will probably exclude or irritate someone with a valid response that I hadn't considered e.g. some of the international post/zip codes.

I want to construct a general validation script and use it on many similar general enquiry forms.

Nick_W I like the article you posted: http://www.webmasterbase.com/article/862
I will start there and see what I can do (as a total beginner to javascript).

If anyone has a good general basic script to post, that would be nice ;)

11:41 am on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Here's one I use to check that a selection has been made and at least one student from a list is selected as well.

function validate() {

var ready = true;

if (document.formSel.orgevent.value=="") {
alert("Please select an event");
document.formSel.orgevent.focus();
ready = false;
}

if (document.formSel.comp1.value=="" ) {
alert("Please enter a composer");
document.formSel.comp1.focus();
ready = false;
}

if (document.formSel.condate.value == "") {
alert("Please enter the contest date");
document.formSel.condate.focus();
ready = false;
}

if (document.formSel.deaddate.value =="") {
alert("Please enter the deadline date");
document.formSel.deaddate.focus();
ready = false;
}

var j=0;
var sally = "";

for (var i=0;i< document.formSel.check.length; i++) {
if (!document.formSel.check[i].checked) {
j++
} else {

sally += document.formSel.gra[i].value + ","

}

}
if (j == document.formSel.check.length) {
alert("Please select at least one student");
ready = false;
}

if (ready) {
document.formSel.mbrs.value = document.formSel.check.length - j

}

if (ready == true) {
printprompt();
document.formSel.gr.value = sally;
document.formSel.submit();
//alert(document.formSel.gr.value);
}

}

12:32 pm on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Regarding dates - rather than allow free form entry, I have 3 drop downs - day/monthname/year - I then use Javascript to check that it's not the 31st of Feb etc. (I also double check on the server in case no javascript)

This prevents all the problems with different separators, day/month order, and year with/without century.

12:46 pm on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I personally hate the three drop downs for the date. I know it works, and I use something similar for a month/year combination (one drop down populated with about 10 years).

I just suffer the slings and arrows and validate like mad on the server side. I am using mySQL so the date needs to be in YYYY-MM-DD format before it hits the DB. So lots of parsing, checking, reformatting, etc.

11:29 pm on Sep 10, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I personally love the three drop downs for the date. I know that the date I enter is not going to be misinterpreted!

Those of us who live in Australia or UK (and probably other places) are constantly annoyed by the way MS products default to the wrong date settings, even if we've specified the correct international settings. We're just as annoyed by how often US sites assume that we're in the US and force the wrong formatting on us. I'm techy so I'm aware of the date issues and I can usually avoid messing it up, but let's face it most users aren't aware that it's such a big issue, and millions enter a date that is correct where they live but gets misinterpreted by the website. (And yes I admit it must also happen with US visitors to UK and Oz sites).

So I go for the simple, clear, as-close-to-foolproof-as-will-ever-be-possible solution. Three drop downs.

1:25 am on Sep 11, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Yes you have a good point there. There is absolutely no confusion with a three drop down system.

But, for business applications, where the end user is "supposed" to be a bit more sophisticated, it looks very amateur to put three drop downs when a date parameter is needed.

My javascript popup calendar is nice because it returns a US formatted date for my US clients (or an alternate formatted date for my alternate clients..). But there is an input box as well if they don't want to use the popup.

I'm not sure there is a 'great' solution, but I'll try the 3 boxes on one page and see what the reaction (if anyone even notices) is.

9:31 am on Sep 11, 2002 (gmt 0)

10+ Year Member



You could have three text input boxes, labelled "month", "date" and "year". You can allow users to enter the month as a figure or a month name (and convert the name to a figure), and a simple algorithm to convert years from two-digit to four-digit format where necessary.

Of course, it does depend on what you need the date for. If it's a birth date, you can assume for the next couple of years at least that the year will be in the 20th century, so that makes two-digit to four-digit format slightly easier. If it's a date in the near future (this might be the case when buying theatre tickets, for example), you can arrange for the form to default to the current date (or to tomorrow's date, perhaps) -- and you can assume that the year is either going to be this year or next. In fact, in these cases you might safely assume that the date to be entered is never going to be more than twelve months in advance, thus obviating the need for the user to enter a year at all.

10:56 pm on Sep 11, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



rewboss, I like your ideas about validation and defaults. Yes, for many situations, it's possible to predict the likely range of dates, and that gives us an opportunity to make things that little bit more user-friendly. (Of course my three drop downs won't be labelled "month", "date" and "year", they'll be labelled "date", "month" and "year" ;) ;) )
2:52 pm on Sep 20, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



OK here's the script I've tried to create for now. Can anyone tell me (total beginner at javascript) where the bug is?

Its only meant to check for email and that a name has been entered. I will worry about other fields when I can get this working.
- If the form is completed without errors first time it sends the info ok.
- The form displays alerts ok.
- The problem is: after it has diplayed alerts and the correct info is then entered (ie name and email) the form doesn't send, it just sits there.

<script type="text/javascript">
function validate()
{
x=document.myForm;
input=x.name.value;
if (input.length<2)
{
alert('Please enter your name at the top of the form')
submitOK="False";
}

f = document.myForm;
if (!(isValidEmail(f.email.value))) {
alert('Please enter your correct email address.');
submitOK="False";
}

if (submitOK=="False")
{
return false;
}
else
{
return true;
}

function isValidEmail(address) {
// long email validating script I have permission to use but I don't think I'm allowed to post here.
// after a bunch of lines it either: return false; or: return true;
// I'm pretty sure the bug is not here as it works ok on its own.
}

}
</script>

5:42 pm on Sep 20, 2002 (gmt 0)

10+ Year Member



You don't show where submit_OK is defined, but my guess is the second time through it still has false in it from the first time through. Try setting it true at the top, then to false if an error is detected.

Ross

6:13 pm on Sep 20, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



RossWal
THANKYOU !

I think its finally working :) ;)

 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month