Checking for empty form fields

When using JavaScript to validate form input one might be tempted to use:

if(document.form.field.value == '') {
alert("Hey, enter a value");
return false;

– or –

if(document.form.field.value.length == 0) {
alert("Hey you, yes you the guy who pressed enter or clicked 'Submit', enter a value");
return false;

The problem with these two methods is that they don’t prevent the user from just tapping the spacebar within the field to be validated.
A slightly more sophisticated approach is the following regex, which checks for the presence of alphanumeric characters.

if(document.form.field.value.match(/\w/) == null) {
alert("Please enter something in the field before you hit the submit button again");
return false;

This entry was posted in General. Bookmark the permalink.

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/5/d154205736/htdocs/wordpress/wp-includes/class-wp-comment-query.php on line 405

Comments are closed.