如何使用javascript显示提交时的所有错误

时间:2017-12-19 10:19:20

标签: javascript forms validation

我想知道如何在用户提交表单时一次显示所有已验证的错误。直到这里,它工作正常,但它一个接一个地显示错误。

const form = document.getElementsByTagName('form')[0];
let errorMessages = [
                    "please fill in your name here", 
                    "please, fill in your email correct here", 

                    ];
const reg = /^\d+$/;

form.addEventListener('submit', function(e){
    if(valName.value !== ''){
        valName.nextElementSibling.textContent = '';
        valName.className = '';
    } else {
        e.preventDefault();
        valName.nextElementSibling.textContent = errorMessages[0];
        valName.className = 'errorborder';
        return false;
    }
    if(valEmail.value.indexOf('@') != -1 && this.value.indexOf('.') != -1){
        valEmail.nextElementSibling.textContent = '';
        valEmail.className = '';
    } else {
        e.preventDefault();
        valEmail.nextElementSibling.textContent = errorMessages[1];
        valEmail.className = 'errorborder';
        return false;
    }
});

提前多多感谢!

2 个答案:

答案 0 :(得分:1)

您可以将所有错误存储在字符串变量中,并一次显示所有错误。

Error{FacebookServiceException: httpResponseCode: -1, facebookErrorCode: 1611072, facebookErrorType: null, message: Action
 Requires At Least One Reference: The action you're trying to publish
 is invalid because it does not specify any reference objects. At least
 one of the following properties must be specified: victory.

答案 1 :(得分:1)

你必须删除你的回报 - 否则代码将停在那里。 我还将代码转换为函数而不是复制。

    const form = document.getElementsByTagName('form')[0];
    let errorMessages = [
                        "please fill in your name here", 
                        "please, fill in your email correct here", 

                        ];

    const reg = /^\d+$/;

    function isEmailValid(email){
        return email.indexOf('@') != -1 && email.indexOf('.') != -1;
    }

    function isNameValid(name){
        return name !== ''
    }

    function setErrorMessage(el, errorMessage){
        el.nextElementSibling.textContent = errorMessage;
        el.className = 'errorborder';
    }

    function clearError(el){
        el.nextElementSibling.textContent = '';
        el.className = '';
    }

    form.addEventListener('submit', function(e){
        var validName = isNameValid(valName.value);
        var validEmail = isEmailValid(valEmail.value);

        if(!validName){
            setErrorMessage(valName, errorMessages[0]); 
        }else{
            clearError(valName);
        }

        if(!validEmail){
            setErrorMessage(valEmail, errorMessages[1]); 
        }else{
            clearError(valEmail);
        }

        if(!validName || !validEmail) {
            e.preventDefault(); 
            return false;
        }
    })