我编写了一个自定义JavaScript验证器,它需要在每个连接到输入的keyup事件上运行,并为每个输入字段运行vacillator()。
问题是它只适用于加载。 我想参加每个关键活动。 这是一个jsfiddle https://jsfiddle.net/vo1npqdx/717/
function display_error(elem, message) {
elem.insertAdjacentHTML('afterend', "<label class='js-error' style='color:red;' >" + message + "</label>");
}
function check_error(elem) {
error_label = elem.nextElementSibling
if (error_label && error_label.classList.contains('js-error')) {
return true;
}
}
function add_error(elem,message) {
if (!check_error(elem)){
display_error(elem, message)
}
}
function delete_error(elem) {
if (check_error(elem)){
elem.nextElementSibling.remove();
}
}
function validateForm(elem) {
alert("Checking if form is vaild")
// If input type == text
if (elem.getAttribute("type") == 'text') {
//alert("elemcent is text")
maxlength = elem.getAttribute("maxlength")
minlength = elem.getAttribute("minlength")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (minlength) {
// if value is under min length
if (elem.value.length < parseInt(minlength)) {
// add errors
add_error(elem, data_error)
//alert("above min length")
} else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
// if input type == number
if (elem.getAttribute("type") == 'number') {
//alert("element is text")
max = elem.getAttribute("max")
min = elem.getAttribute("min")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (min) {
// if value is under min length
if (elem.value < parseInt(min)) {
// add errors
add_error(elem, data_error)
//alert("Belove Min Number")
}
else if(elem.value > parseInt(max)){
// add errors
add_error(elem, data_error)
//alert("above Max number")
}
else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
}
// Desired Result
// if keyup
// for input in inputs:
// someFunc(input) that makes input tags red
var inputs = document.getElementsByClassName('form-control');
for(var i=0;i<inputs.length;i++){
elem = inputs[i]
elem.addEventListener('keyup', validateForm(elem))
}
答案 0 :(得分:2)
您正在立即呼叫您的事件处理程序。它需要用函数包装。所以这个:
elem.addEventListener('keyup', validateForm(elem))
应该是:
elem.addEventListener('keyup', function(event) {
// do something with event
validateForm(this);
});