Checking a form with JavaScript

You can alert your user immediately if anything in a form is improperly filled out, by using JavaScript. You would want to check only that the required elements are filled in, and filled in reasonably, for instance, an email address ought to have an at sign (@).

It is most convenient to call a function to do this, either one you write yourself, or one written ( and tried out by) someone else, such as me. The basic strategy is:

  1. You add an onSubmit action to the form. This is JavaScript that is called when the submit event occurs (that's when the user clicks the submit button).
  2. onSubmit needs to call a function, that calls one or more other functions, that do the actual checking. If they all return the value true, then the master function also returns true, else it returns false
  3. Your onSubmit action also needs to return this value, if it is false, the form will not be submitted.
  4. Note: In case JavaScript is disabled, no checking can be done, and the form will always be submitted. That is why our php scripts must still check too.

Simple Do it Yourself method

Put these functions in your head section:
<script>
function isFilled(aname) // requires a field not be left empty
{
if (aname.value =="") // value left empty
{ alert(aname.name + " is blank"); // name of the field
aname.focus();
return false; //don't want to submit
}
else
return true;
}

function checkform(theform) //check all required fields
{ ok = (isFilled(theform.who)) // if all is okay, submit
return ok
}
</script>
isFilled is appropriate for input fields (types text and password), and textarea's. It cannot check groups of radio buttons.

In checkform, you need to call one or more functions to do checking. In this example, a single input with name="who" is to be checked. Change "who" to whatever name you gave to your required input field. Should you have other elements to check, use the and (&&) operator for as many functions as you wish, for example:
ok = (isFilled(theform.name) && isFilled(theform.email) )
Checking will stop with the first problem found, after isFilled puts up an alert box. It does this, I hope you see, if the value in the field is blank. checkform returns a value of true or false

Now all that is left to do is to use an onSubmit

 <form action="..." 
onSubmit="return checkform(this)"

Note that:

A "no hands" approach for more elaborate checks.

However, you might want to check select lists, or radio buttons, numbers, or for reasonable-looking email or phone. You could get buried in detail. So use Lin Jensen's handy functions:
Function name
useful for
what it  does
filled
text, textarea
can't be blank
isInt
text
require a whole number
isFloat
text
require a real number
isPhone
phone number
needs 822 and 1234
isMail
email address
Of the form: me@here.ca
isPostalCode
Postal Code
valid Canada (H0H 0H0) or USA (94708)
selectionMade
Select list
single: not first (dummy) option
multiple: at least one option selected
prepareForm
Form to be checked
Prepares form to have other check methods assigned
checkForm
onSubmit function
Lets form submit if everything ok

Are you ready? First, you don't need to see the functions, just know how to use them. Include them in the head of your document:

<script src="/jensen/checker.js">	// standard check functions, & checkForm
</script> (src="https://osiris.ubishops.ca/jensen/checker.js" -- if you want to test it locally)
As in the simple example, in the form tag include the onClick function, which  is now checkForm (yes, I have now adopted the Java usage of capitalizing additional "words" in a name)
  <form action="..." 
onSubmit="return checkForm(this)"

Now the tricky part. After the form is defined (after the </form>) we need to prepare the form, by giving a default check method to every form element. In other words, when checkForm does its work, all elements will be considered ok.

<script>	// now that the form is defined,
// add a default check method to EVERY element
prepareForm (document.LinForm);

Only in place of "LinForm" you put the name of your form. If you didn't name your form, go back to the <form ...> tag and give it a name. Or you can use document.forms[0], providing it is the first form on the page.
Now, decide which form elements you need to have checked. In my example, I checked everything, because it is an example of how to check everything I could think of. Normally you want to be more relaxed. To require a comment, for example, just invites comments of the form, "asdf qqqwerty." This is an example of what you do. Of course you use the names you have assigned to your form and its elements:

   with (document.LinForm) {	// add check methods for required elements
age.check = isInt
comment.check = filled
phone.check = isPhone
drink.check = selectionMade
elements['fruit[]'].check = selectionMade
}
</script>

Fruit is a select-multiple. This is no problem, except that PHP requires a name of 'fruit[]', which causes syntatic problems for javascript. Hence I was unable to write: fruit[].check, fortunately, there is an alternative. This method also works for a name containing a space,

        elements['first name'].check = filled   // space is awkward

Fine Tuning

Button groups (radio, checkbox)

Perhaps you noticed I omitted groups of radio buttons. I have a function for that too, but you cannot attach it directly. The same function works for a group of checkboxes with all the same name. In my case the group is named "colour", while tree[] is the name of a group of checkboxes. To require one of a group to be checked, include the group(s) as extra arguments of checkForm:
	onSubmit="checkForm(this, this.colour, this.elements['tree[]'])"

Immediate feedback

Once a field is changed, one might want to check its validity right away, instead of waiting for the submit button. Is it a reasonable email address, for example? To do this, the input itself can have an onChange, like this:
e-mail <input name="email" onChange="this.check()">

Custom alerts

Provided you use meaningful names, the Alert messages should be reasonable. But if you would like to compose your own, I have made this possible, do this by sepcifying a .warning property. For example, instead of "Please choose a colour", I wanted this to appear:
And for a "group" of checkboxes, even this doesn't quite work, since html is unprepared, however, it suffices to attach the warning to the first checkbox:
	colour.warning = "We want to know your favourite colour!"
colour[0].warning = "We want to know your favourite colour!" // this is needed for chromium browser!
elements['tree[]'][0].warning = "We insist that you plant at least one kind of tree this fall!"