用JS OnSubmit验证HTML形式



我的表单上有一个选项元素,在上面和电子邮件字段。

<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
    <div class="form-group">
        <h4>Bitte tragen Sie die folgenden Daten ein</h4>
        <div class="form-group">
            <label for="versandart">Versandart</label>
            <select class="form-control" id="versandart" name="versandart" autofocus>
                <option value="both">E-Mail und Druck</option>
                <option value="onlyEmail">Nur E-Mail</option>
                <option value="onlyPrint">Nur Druck</option>
            </select>
        </div>
        <div class="form-group">
            <label for="email">E-Mail</label>
            <input type="email" class="form-control" id="email" placeholder="email" name="email">
        </div>
        <button class="btn" type="submit">Versenden</button>
    </div>
</form>

根据用户选择的内容,我必须检查"同时"one_answers" OnlyEmail"中是否输入了电子邮件地址。因为在所有3例情况下都不需要电子邮件,所以我无法将HTML的所需元素用于电子邮件字段。因此,我试图在这样的提交事件上对其进行测试:

 document.querySelector('form[name="send"]').addEventListener("submit", validateFields);
function validateFields(){
    var versandart = document.getElementById("versandart");
    var email = document.getElementById("email");     
    if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
        if(email.value == ''){
            email.setCustomValidity('EMail muss eingegeben werden');
            return false;
        }else if(CHECK HERE if Mail is not correct){
            email.setCustomValidity('EMail format is not correct');
            return false;
        }else{
            //in this case email is not empthy and is correct
            return true;
        }
    }
}

但这是不起作用的,因为我覆盖标准HTML检查有效的电子邮件地址。因此,我必须在"如果邮件不正确的情况下检查此处检查"。

我该怎么做,那是正确的方法吗?还是我应该在versandart字段中添加一个onchangelistener,如果所选值适合前两种情况?

,则将所需的标签添加到电子邮件字段中?

在您的其他情况下,请使用isEmail()函数这样:

else if(email.value.isEmail()) {
    return true;
    // Now the form will get submitted to the PHP script.
}

string.isEmail()如果输入的模式与电子邮件地址匹配,则返回true。

但是,请不要忘记执行服务器端形式验证。如果裂纹器关闭JavaScript,则如果您只有JavaScript验证,它们可能会在系统中引起混乱 - 尤其是因为您显然无法将所需的HTML属性用于电子邮件输入。

最新更新