3
\$\begingroup\$

Please help me to improve the JavaScript validator plugin by making it more OO and robust. Requirement is to trigger the validation if there is an attribute data-formValidate present in the input tag.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>SignUp</title>
    <style>
    .error {
        margin-bottom: 5px;
        color: red;
    }
    </style>
</head>
<body>
  <div class="container">
    <h1>Signup Form</h1>
    <form id="main" action="" method="post" novalidate>
      <div>
        <label>Name: </label>
          <input data-formValidate="string" id="name">
        <p class="messages"></p>
      </div>
    <div>
        <label>Password: </label>
          <input data-formValidate="password" type="password" id="password">
        <p class="messages"></p>
      </div>
      <div>
        <label>Email: </label>
        <input data-formValidate="email" id="email">
        <p class="messages"></p>
      </div>
    <div>
        <label>Phone: </label>
        <input data-formValidate="phone" id="phone">
        <p class="messages"></p>
      </div>
      <div>
            <button type="submit" class="btn btn-default">Submit</button>
      </div>
    </form>
  </div>
  <div>
    
  </div>
  <script>
    (function() {
    
        var form = document.querySelector("form");
        form.addEventListener("submit", function(evt) {
            evt.preventDefault();
            startValidation();
            return false;
        });
    
        startValidation();
        function startValidation() {

            var inputs = document.querySelectorAll("input")
            for (var i = 0; i < inputs.length; ++i) {
                if(inputs[i].getAttribute('data-formValidate')) {
                    inputs.item(i).addEventListener("change", function(ev) {
                        var errors = validator(inputs);
                        showErrorsForInput(this, errors[this.getAttribute('data-formValidate')])
                    });
                }
            }
        }
        
        function emailValidator() {
            var value = input.value;
            var regString = /^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i;
            var pattern = new RegExp(regString);
            if(!pattern.exec(value)) {
                return ["Not a valid email"];
            }
        }
        
        function passwordValidator(input) {
            if(input.value.length <= 6 ){
                return ["Password is too short!"];
            }
        }
        
        function phoneValidator(input) {
            if(isNaN(input.value) || input.value.length !=10 ){
                return ["please enter a valid telephone number!"];
            }
        }
      
        function validator(inputs) {

            var error_messages = {};
            for (i = 0; i < inputs.length; ++i) {
                input = inputs.item(i);
                if(input.getAttribute('data-formValidate') === 'email') {
                    error_messages.email = emailValidator(input);    

                } else if(input.getAttribute('data-formValidate') === 'password') {
                    error_messages.password = passwordValidator(input);
                    
                } else if(input.getAttribute('data-formValidate') === 'phone') {
                        error_messages.phone =  phoneValidator(input);
                        
                }
            }
            
            return error_messages;
        }
        
        
        function showErrorsForInput(input, errors) {
            var messages = input.parentNode.querySelector(".messages");
            resetMessages(input.parentNode);
            if (errors) {
                input.parentNode.classList.add("add-error");
                errors.every(function(error) {
                    showError(messages, error);
                });
            } else {
                input.parentNode.classList.add("success");
            }
        }
      
        function resetMessages(parentNode) {
            parentNode.classList.remove("add-error");
            parentNode.classList.remove("success");
            var errors = parentNode.querySelectorAll(".error");
            for(var i =0; i < errors.length; i++) {
                errors[i].parentNode.removeChild(errors[i]);
            }

        }
      
        function showError(messages, error) {
            var ptag = document.createElement("p");
            //ptag.classList.add("help-block");
            ptag.classList.add("error");
            ptag.innerText = error;
            messages.appendChild(ptag);
        }
      
    })();
    </script>
</body>
</html>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.