Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1718 How can I reject a form submission if one of any number of validate functions returns false?

You are here: irt.org | FAQ | JavaScript | Form | Q1718 [ previous next ]

The following invokes the validate1() and validate2() functions to ensure that the text entered in the text form field is an integer. The validate1() function allows 1.0 as a valid entry, whereas the validate2() function does not. The validate2() function is only invoked if validate1() returns true. Thus is validate1() returns false, the execution of validate2() is skipped, and the form submisson cancelled. If validate1() returns true, but validate2() returns false then the form submission is again cancelled. Only if both functions return true is the form submitted. Additional functions may be appended to the test so long as a boolean And (&&) is included between each function call:

<html>

<head>

<script language="JavaScript"><!--
function isInteger(value) {
  return (parseInt(value) == value);
}

function validate1(form) {
  if (!isInteger(form.myField.value)) {
    alert('Invalid integer value entered');
    return false;
  }

  return true;
}

var integer = /^\d+$/;

function validate2(form) {
  if (window.RegExp && !integer.test(form.myField.value)) {
    alert('Invalid integer value entered (regular expression)');
    return false;
  }

  return true;
}
//--></script>

</head>

<body>

<form onsubmit="return (validate1(this) && validate2(this))">
<input type="text" name="myField">
<input type="submit" value="Submit">
</form>

</body>

</html>

©2018 Martin Webb