Not-null validation for multiple input fields in the same form

Directly on the code, the structure is as follows:

<form id="user">
        <ul class="form">
            <li>
                <div class="th">姓名:</div>
                <div class="td">
                    <input type="text" class="ipt" value="请输入姓名">
                    <div class="tips">
                        <span>Name cannot be empty</span>
                    </div>
                </div>
            </li>
            <li>
                <div class="th">手机:</div>
                <div class="td">
                    <input type="text" class="ipt" value=" ">
                    <div class="tips">
                        <span>Please fill in the phone number</span>
                    </div>
                </div>
            </li>
            <li>
                <div class="th">Email:</div>
                <div class="td">
                    <input type="text" class="ipt" value="  " id="email">
                    <div class="tips">
                        <span>Please fill in the email address</span>
                    </div>
                </div>
            </li>
            <li>
                <div class="btn-area">
                    <button type="button" class="btn btn-commit">提交</button>
                </div>
            </li>
        </ul>
    </form>

Script implementation:

/**
 * remove trailing spaces
 * @param {String} str String to remove leading and trailing spaces
 * @return {String} string with spaces removed
 */
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
/**
 * Required field validation of the form
 * @return {Boolean} true or false
 */
function formEmptyCheck() {
    // Get the input box that needs to be validated, not limited to this line of code to get the corresponding element
    var formElements = document.getElementById("user").getElementsByClassName("ipt");
    for (var i = 0; i < formElements.length; i++) {
        if (!trim(formElements[i].value)) {
            formElements[i].focus();
            return false;
        }
    }
    return true;
}


var btnCommit = document.getElementsByClassName("btn-commit")[0];
btnCommit.onclick = formEmptyCheck;
What is done here is not only a non-empty verification, but also a function to remove the trailing spaces in the input content of the input box, because in most cases, the data we want to obtain generally does not want to have spaces before and after, which is meaningless. Here's a little extra feature. The non-empty client-side validation of multiple input fields in the same form has been implemented here, and some corresponding operations can also be performed for each illegal input item as needed, such as input prompts and the like.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325811672&siteId=291194637