Внимательно прочитайте комментарии.
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
/* <Array> allClasses = a list of all separate class names of `thisTag`*/
/* This loop walks through all elements of the `allClasses` array, and
* calls the `validBasedOnClasses` function (defined below). The return
* value of the function is added to `outClass`, together with a space " "*/
for (var j=0; j<allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
/*The class attribute of the element is set to the string `outClass`*/
thisTag.className = outClass;
/*Can the string "invalid" be found in the `outClass` string? */
if (outClass.indexOf("invalid") > -1) {
thisTag.focus();/* Puts the user focus to the element*/
if (thisTag.nodeName == "INPUT") {
/* Selects everything in the input, so that the user can easily
* overwrite the contents of the input field*/
thisTag.select();
}
return false; /*Invalid, return FALSE*/
}
return true; /*Valid, return TRUE*/
/* <function> validBasedOnClass - a function used above
* This function accepts a parameter, which equals one of the class names
* of the element */
function validBasedOnClass(thisClass) {
var classBack = ""; /* <string> classBack. This string will be returned*/
switch(thisClass) {
case "": /* An empty class name - Nothing to check*/
case "invalid": /* "invalid" - Remove this class, so that the
* code can validate again (when the "reqd" class
* is encountered) */
break;
case "reqd": /* class name == "reqd" */
/* <boolean> `allGood` is defined at the main function.
* This function will only mark the FIRST invalid input field
* as defined in this function, and the main function */
if (allGood && thisTag.value == "") {
classBack = "invalid "; /*Return class "invalid"*/
}
classBack += thisClass;
/* `classBack` now holds "invalid reqd" or "reqd" */
break;
default:
classBack += thisClass; /* Unknown class, ignore it */
}
return classBack; //Return the (altered) class
}
}
Примечание: allGood
- это переменная, определенная в основной функции (validForm
):
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i=0; i<allTags.length; i++) { /*Walks through all elements*/
if (!validTag(allTags[i])){ /*Checks whether an element is invalid or not*/
allGood = false;
/* `allGood` = false, notifies <function> allTags that an invalid
* element has already been detected. */
}
}
return allGood;
... //function validTag below
Ваш фрагмент кода будетпроверить элементы и сосредоточиться на первом элементе, который является недействительным.