Holly Johnson Holly Johnson - 4 months ago 17
Javascript Question

Plain Javascirpt Custom Vaildation Run Vaildation on keyup

I wrote a custom JavaScript validator that needs to run on every keyup event that is attached to ever input and runs the vacillator() for every input field.

Problem is that it only works on load.
I want to to work on every key-up event.
Here is a 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))

}

Answer Source

You are calling your event handler straight away. It needs to be wrapped with a function. So this:

elem.addEventListener('keyup', validateForm(elem))

should be:

elem.addEventListener('keyup', function(event) {
    // do something with event
    validateForm(elem);
});