onsubmit
with Regular ExpressionsJavascript regular expressions use the same syntax as Perl. However, the syntax of the matching operations is different. The following example tests whether the first form field contains at least one alphabetical character (using a character class declaration, i.e. [a-zA-Z]+
) and whether the second field contains 5 digits (using a pre-defined character class and a quantifier, i.e. \d{5}
).
The validation is controlled by a flag variable, return_val
. It is initialized to the boolean value true
when the validation function is called, but is set to false
if any of the validation tests fail.
The validation function returns return_val
; if it is false
, the browser will not send the form to the server. Only if the function returns true
will the data be sent.
<script type="text/javascript"> <!-- // variables of global scope var return_val = ''; var message = ''; var regex = ''; var regex_result = ''; function validateForm(field1, field2) { return_val = true; if (field1.value.length == 0 ) // first, test that both fields contain data { message = "Entry field " + field1.name + " is required." return_val = false; } else if (field2.value.length == 0 ) { message = "Entry field " + field2.name + " is required." return_val = false; } else { regex = /[a-zA-Z]+/; // test for at least one alphabetical characters regex_result = field1.value.match(regex); // if the match operation DID NOT find // alphabetical characters, regex_result // will be 'null' if (regex_result == null) { message = "Entry field 1" + field1.name + " does not contain word characters." field1.value = ''; return_val = false; } regex = /\d{5}/; // test for at least one alphabetical characters regex_result = field2.value.match(regex); // if the match operation DID NOT find // digits, regex_result will be 'null' if (regex_result == null) { message = "Entry field 2" + field2.name + " needs a zip code of five digits." field2.value = ''; return_val = false; } } if (return_val == false) { alert(message); // print error message to pop-up window } return return_val; } //--> </script>