From 67d79a907ec0773cd471f53a76f8e9c7f056ecc7 Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Sun, 4 Jan 2009 23:16:54 +0000 Subject: [PATCH] After a javascript validation error from a form submission, focus on the first errored field git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.2@69634 467b73ca-7a2a-4603-9d3b-597d59a354a9 --- forms/Validator.php | 3 ++- javascript/Validator.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/forms/Validator.php b/forms/Validator.php index 98afb7b75..62f254700 100755 --- a/forms/Validator.php +++ b/forms/Validator.php @@ -91,9 +91,10 @@ Behaviour.register({ validate : function(fromAnOnBlur) { initialiseForm(this, fromAnOnBlur); $code - + var error = hasHadFormError(); if(!error && fromAnOnBlur) clearErrorMessage(fromAnOnBlur); + if(error && !fromAnOnBlur) focusOnFirstErroredField(); return !error; }, diff --git a/javascript/Validator.js b/javascript/Validator.js index bdc887a8f..48add3fb9 100755 --- a/javascript/Validator.js +++ b/javascript/Validator.js @@ -1,7 +1,9 @@ var _CURRENT_FORM; +var _FIRST_ERRORED_FIELD = null; function initialiseForm(form, fromAnOnBlur) { _CURRENT_FORM = form; + _FIRST_ERRORED_FIELD = null; if(fromAnOnBlur) { limitValidationErrorsTo(fromAnOnBlur); @@ -17,6 +19,13 @@ function hasHadFormError() { return _HAS_HAD_FORM_ERROR || !_ERROR_CACHE; } +function focusOnFirstErroredField() { + try { + _FIRST_ERRORED_FIELD.focus(); + } catch(er) { + } +} + /** * Returns group with the correct classname */ @@ -251,6 +260,9 @@ function validationError(field,message, messageClass, cacheError) { // Keep a reference to it field.validationMessage = validationMessage; + // Keep a reference to the first errored field + if(field && !_FIRST_ERRORED_FIELD) _FIRST_ERRORED_FIELD = field; + // Set the attributes validationMessage.className = "message " + messageClass; validationMessage.innerHTML = message;