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

时间:2016-07-21 18:38:20

标签: php forms validation

在用户输入时,我一直在寻找一种方法来验证我的表单。例如,我想要一个邮政编码字段。我希望用户在字段下方看到一条消息,说明他们已超出此字段的字符数限制,但在提交表单之前。怎么办呢?

使用此类代码:

ID

1 个答案:

答案 0 :(得分:2)

试试这个:

<强> 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');
    }
});

编辑说明:

var input定位您的first_name输入

addEventListener进行事件检测。通过参数&#39; keydown&#39;,JavaScript将听取按键。

classList是一个操纵类的API(IE不支持)。

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