0

I need to implement code which should add eventlistener and on change event check if the form is valid and add the message

let validate = function(element, info, functionValidate) {
    
    let htmlTag = document.querySelector('fieldElem');//?
    htmlTag.addEventListener('change',ev=>{
    let notif = document.createElement('span');
        document.htmlTag.appendChild(notif);//should add span element next to input

        if(fieldElem.value == '')
        {
            notif.style.visibility = "hidden"; //hide span if nothing happens
        }
        //I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...

1 Answer 1

0

Try the following. You could also use form validation (see Form Validation Set Custom Validity for an example)

function validator(val) {
  return (val != '');
}

function validateField(element, validator, message) {

  var helper = document.createElement("span");
  var parent = element.parentElement;
  parent.appendChild(helper);
  
  
  element.addEventListener('change', function() {
    var val = element.value;
    if (!validator(val)) {
      helper.innerText = message;
    } else {
      helper.innerText = "";
    }

  });

}

validateField(document.getElementById('test'), validator, 'Wrong input');
<html>

<body>
  <form>
    <input id="test" type="text" placeholder="Type here"/>
  </form>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.