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

Q1412 How can I validate a form field using onBlur and if necessary halt the submission of the form if the user has clicked on the submit button - which caused the original onBlur event to be fired?

You are here: irt.org | FAQ | JavaScript | Event | Q1412 [ previous next ]

Two events have been fired: onBlur and onSubmit. I'm not sure which one is fired first - it may be impossible to predict. You need to be able to cancel the onsubmit event from the onBlur event. The only way to do this is by creating a global boolean variable that the onSubmit event handler checks to see if the combination of and onFocus/onBlur event have validated the field data. If not then the onSubmit handler needs to return false (effectively cancelling the form submission). It then gets a bit more complicated, as once the onBlur event handler has validated the field data, it may need to start the form submission over again, so it need to know that there was an attempt to submit the form. Therefore we need yet another global boolean variable that the onSubmit handler sets to true just before returning false.

Hopefully the following example code does all the above:

<script language="JavaScript"><!--
var booleanSubmitted = false;
var booleanFocused = false;

function validateSubmit() {
    if (booleanFocused) {
        booleanSubmitted = true;
        return false;
    }
    booleanSubmitted = false;
    return true;
}

function focusSet() {
    booleanSubmitted = false;
    booleanFocused = true;
}

function validateBlur(ref) {
    if (ref.testField.value == '') {
        // invalid, refocus form field
        ref.testField.focus();
    }
    else {
        // valid, clear boolean
        booleanFocused = false;
        // test for submit
        if (booleanSubmitted) {
            // clear boolean
            booleanSubmitted = false;
            // submit form again (doesn't trigger onSubmit)
            ref.submit();
        }
    }
}
//--></script>

<form name="testForm" onSubmit="return validateSubmit()">
<input name="testField" type="text" onFocus="focusSet()" onBlur="validateBlur(this.form)">
<input type="submit">
</form>

©2018 Martin Webb