如何在运行时创建表单验证错误消息


How to create Form validation error message at runtime?

我已经搜索了几个小时,试图找到一种在用户输入时验证表单的方法。例如,我想要一个邮政编码字段。我希望用户在提交表单之前,在字段下面看到一条消息,说明他们已经超出了该字段的字符限制。如何做到这一点?

带有这样的代码:

<form method="POST" name="wrriregistration" target="_blank"><center>
<table width="100%">
<tbody>
<tr>
<td width="149"><strong>*First Name:</strong></td>
<td width="229"><input type="text" name="first_name" size="35" maxlength="100"/></td>
<td width="123"><strong style="display:none;">Middle Initial:</strong></td>
<td width="659"><input style="display:none;" type="text" name="middle_initial" size="35" maxlength="50" /></td>
</tr>
</tbody>
</table>
</form>

试试这个:

HTML

<input type="text" name="first_name">
<div id="error">
    My custom error
</div>

CSS

#error {
    display: none;
}
#error.show {
    display: block;
}
input {
    color: #000000;
}
.invalid {
    color: #FF0000;
}

JS

var input = document.querySelector('[name="first_name"]');
var error = document.getElementById('error');
input.addEventListener('keydown', function(){
    // Whatever you want
    if(this.value.length >= 10) {
        this.classList.add('invalid');
        // You can control style of your invalid input with .invalid
        error.classList.add('show'); // Display your custom error
    } else {
        this.classList.remove('invalid');
        error.classList.remove('show');
    }
});

EDIT说明:

var input针对您的first_name输入

CCD_ 2进行事件检测。通过参数"keydown",JavaScript将监听按下的键。

classList是用于操作类的API(IE不支持)。

请在此处尝试:https://jsfiddle.net/e3oe4ykf/