表单验证出错与数据上报跟踪实例页面

回到相关文章 »

效果:

昵称:

邮箱:

性别:

提前打开控制台,Network → Img,clear已有请求,然后点击注册查看请求

代码:

CSS代码:
.track:invalid {
    background: url(./pixel.gif?action=regist&status=invalid);
}
.track:valid {
    background: url(./pixel.gif?action=regist&status=valid);
}
HTML代码:
<form novalidate>
    <p>昵称:<input class="nickname" required></p>
    <p>邮箱:<input type="email" required></p>
    <p>性别:<input type="radio" id="male" name="sexy" value="male" required><label for="male">男</label>
        <input type="radio" id="female" name="sexy" value="female" required><label for="female">女</label>
    </p>
    <p><button type="submit">注册</button></p>
</form>
                
JS代码:
document.forms[0].addEventListener('submit', function (event) {
    event.preventDefault();
    // 上报成功与否
    this.classList.add('track');
    // 这个是不影响原生表单的提交行为,实际开发多走Ajax
    if (this.reportValidity()) {
        this.submit();
    }
    setTimeout(function () {
        this.classList.remove('track');
    }.bind(this), 0);    
});