javascript проверка формы - несколько форм в одном документе - передача 1 формы за раз - PullRequest
0 голосов
/ 11 июля 2020

У меня эта программа была в основном завершена, но при исправлении некоторых проблем с вводом данных c с указанием типа я испортил последнюю функцию, которая отправляет форму, когда нет сообщений об ошибках.

Предполагается для отправки только формы, содержащей нажатую кнопку отправки. Мой код ниже, а также изображение этого последнего шага в отладчике. В принципе, похоже, что это должно быть нормально, чтобы отправить единственную форму, над которой работает, повторяется через функции, чтобы подтвердить ее выполнение, но затем обновляется вся страница. debugger before finish

If any1 can read thru this and help me find what I'm missing, I'd b very appreciative.

Javascript:

/**
 * wait for all other content to load before javascript
 * @param {*} event.onload
 */
window.onload = () => {
    document.addEventListener("submit", (event) => {
        event.preventDefault() //stop page refreshes
    });
    /**
     * turn off page submits for all submit buttons, replace with validate function listeners
     */
    const armSubmits = () => { //handle the submit buttons
        let submitBtn = document.getElementsByName("submitBtn");
        for (let s = 0; s < submitBtn.length; s++) {
            submitBtn[s].addEventListener("click", (event) => {
                event.preventDefault() //turn off defaults
            });
            submitBtn[s].addEventListener("click", validate); //plug validates
        }
    }
    armSubmits(); //initiate armSubmits
}
/**
 * initiate validation process, starting from validate button location
 * @param {*} event 
 */
const validate = (event) => {
    const parentForm = event.target.parentElement.parentElement;
    let submitBtn = document.getElementsByName("submitBtn");
    for (let s = 0; s < submitBtn.length; s++) {
        if (submitBtn[s] == event.target) { //selected validate button
            const submitIndex = s;//used to track location of submission
            createErrorDivs(parentForm, submitIndex);
        }
    }
}
/**
 * format error div, ul; keep track of form via submitIndex
 * @param {HTMLElement} parentForm
 * @param {HTMLElement} submitIndex
 */
const createErrorDivs = (parentForm, submitIndex) => {
    let errorDivs = document.getElementsByClassName("errors")[submitIndex]; //track form
    errorDivs.innerHTML = ""; //clear in case of prior processing
    errorDivs.id = `error-div-${submitIndex + 1}`; //id, just in case
    let errorList = document.createElement("ul");
    errorList.id = `error-list-${submitIndex + 1}`;
    errorList.style.color = "red"; //red, as per order
    errorDivs.appendChild(errorList); //add list to div
    inputVerify(parentForm, errorList); //move to following function
}
/**
 * verify each input item on selected form by each specified validation
 * and submit form when completely validated
 * @param {HTMLElement} parentForm 
 * @param {HTMLElement} errorList
 */
const inputVerify = (parentForm, errorList) => {
    let inputs = parentForm.getElementsByTagName("input");
    inputs.length = inputs.length - 1;
    for (let i = 0; i < inputs.length; i++) { //test each input
        errorRequired(inputs[i], errorList); //against each validation requirement
        errorNum(inputs[i], errorList);
        errorLength(inputs[i], errorList);
        errorUsername(inputs[i], errorList);
        errorMin(inputs[i], errorList);
        errorDate(inputs[i], errorList);
        errorPhone(inputs[i], errorList);
        errorPassword(inputs[i], errorList);
        errorAbc(inputs[i], errorList);
    }
    if (errorList.innerText == "") { // if there are no error messages,
        parentForm.submit();
    }
}
/**
 * add errors as they are found to the selected error list
 * @param {HTMLElement: UL} errorList
 * @param {string} errorMsg
 */
const addError = (errorList, errorMsg) => {
    if (errorList.innerHTML.includes(errorMsg)) { //no duplicates
        return;
    }
    let errorMsgNode = document.createTextNode(errorMsg);
    let errorItems = document.createElement("li"); //creating list item
    errorItems.appendChild(errorMsgNode);
    errorList.appendChild(errorItems);
}
/**
 * validate for blank entries
 * @param {HTMLElement} input (for all additional requirement-checking functions)
 * @param {HTMLElement} errorList (for all additional requirement-checking functions)
 */
const errorRequired = (input, errorList) => {
    if (input.classList.contains("required") && input.value.match(/^\s*$/)) {
        let errorMsg = "Required fields must have a value that is not empty or whitespace.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly non-alphabetical entries
 */
const errorAbc = (input, errorList) => {
    if (input.classList.contains("alphabetic") && input.value.match(/[^a-zA-Z]/)) { //if empty + not required, no error message
        //use of Regular Expressions to prevent submit if non-letter characters are included. (I didn't include accented or "nonlatin" characters.)
        let errorMsg = "Alphabetic fields must be a series of alphabetic characters.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly non-numerical entries
 */
const errorNum = (input, errorList) => {
    if (input.classList.contains("numeric") && input.value.match(/[^\d]/)) {
        //Use of Regular Expression to specify digits (integers) only, so no decimal character
        let errorMsg = "Numeric fields must be a series of numbers.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly formatted username entries
 */
const errorUsername = (input, errorList) => {
    if (input.classList.contains("username") && input.value.match(/[^a-zA-Z0-9]/)) {
        //use of Regular Expressions to require alphanumeric entry
        let errorMsg = "Username fields must contain only alphanumeric characters.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly lengthed entries
 */
const errorLength = (input, errorList) => {
    if (input.value === input.defaultValue) {
        return;
    } else if (input.classList.contains("required_size") && input.hasAttribute("minLength") &&
        input.value.length != input.getAttribute("minlength")) {
        let errorMsg = "Field lengths must exactly match the minlength attribute of that field.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for unmet minimum length demand in username
 */
const errorMin = (input, errorList) => {
    if (input.value === input.defaultValue) {
        return;
    } else if (input.classList.contains("username") && input.value.length < 8) {
        let errorMsg = "Username fields must contain at least 8 characters.";
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly formatted date entry
 */
const errorDate = (input, errorList) => {
    if (input.value === input.defaultValue) {
        return;
    } else if (input.classList.contains("date") && !(input.value.match(/^\d{2}\/\d{2}\/\d{4}$/))) {
        //use of Regular Expressions to indicate digits, symbols
        let errorMsg = "Date fields must match the format of XX/XX/XXXX."
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly formatted phone entry
 */
const errorPhone = (input, errorList) => {
    if (input.value === input.defaultValue) {
        return;
    } else if (input.classList.contains("phone") && !(input.value.match(/^\d{3}-\d{3}-\d{4}$/))) {
        let errorMsg = "Phone fields must match the format of XXX-XXX-XXXX."
        addError(errorList, errorMsg);
    }
}
/**
 * validate for incorrectly formatted password entry
 */
const errorPassword = (input, errorList) => {
    if (input.value === input.defaultValue) {
        return;
    } else if (input.classList.contains("password") && !(input.value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/))) {
        //use of Regular Expressions to specify each type of character at least once (0-index) 
        let errorMsg = `Password fields must contain one or more of each of the following types:
        "uppercase letters, lowercase letters, numbers, special characters."`
        addError(errorList, errorMsg);
    }
}

HTML:

<!DOCTYPE html>

<!-- Use this html file to verify your javascript library is functional you should not need to make
any changes to this file for your Javascript library to work -->





    Validation Exercise
     Минимальная длина 5 Требуется  Уровень боли:  Номер, требуемый размер 1  Дата:  Дата  Подтвердить        
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...