Home | All Questions | alt.html FAQ > Client-side Form Scripting

How do I make a form field required?

Add browser-side code (in JavaScript) to check for the presence of a field in the form data, but this cannot really make anything "required" - such checks can easily be bypassed, and often are.

In the form handler, it's usually easy to check for the presence of a nonempty value for a field. Note that if you have, say, <input name="foo"> in a form, then browsers typically _do_ send a field "foo" in the form data, just with an empty value (so it would appear as "foo=", typically). But if you are not actually writing a form handler but just using one, you need to find out whether and how such checks have been coded into it. A simple way to code them is to test for a field with a specific name, and use its value (if present) as a list of required fields, checking that such fields exist in the form data.

In client-side scripting pre-checks - which should only be regarded as something _extra_ and merely a convenience to some users - you could do something like the following:

<script type="text/javascript">
function ok() {
  if(document.myform.foo.value.length > 0)
    return true;
  } else {
    alert('You must include Foo');
    document.myform.foo.focus();
    return false;
  }
}
</script>

<form action="/cgi-bin/zap.pl" onsubmit="return ok()"
name="myform">
Foo: <input name="foo" value="">
 ...
<input type="submit">
</form>

This could be enhanced with some additional checks for the value, e.g. for complying with some specific format (like letters only, or whatever). Note that the attribute value="" is there to make it explicit and sure that the field's initial value is empty and not just undefined. (Probably most browsers use empty initial value anyway, but personally I feel more comfortable when I've made it sure. :-) )

Recommended Resources

Discussion

Related Questions