0

Hello I've just started using javascript and I wanted to implement a function which would call a custom validity message whenever the input is not in the correct format. However it always shows the error message even if the input is correct.

Here's the javascript code:

window.addEventListener('load', function(){

    var in_name = document.getElementById("name");
    var in_surname = document.getElementById("surname");
    var in_email = document.getElementById("email");
    var in_date = document.getElementById("day");
    var today = new Date();

      
    const pt1 = /^[a-zA-Z][a-zA-Z\s]*$/;  
    const pt2 =  /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    
    in_name.onchange = function(){
        if (!pt1.test(in_name))
          in_name.setCustomValidity("Only letters allowed");
        else
          in_name.setCustomValidity("");
    };

    in_surname.onchange = function(){
        if (!pt1.test(in_surname))
          in_surname.setCustomValidity("Only letters allowed");
        else
          in_surname.setCustomValidity("");  
    };

    in_email.onchange = function(){
      if (!pt2.test(in_email))
        in_email.setCustomValidity("wrong format");
      else
        in_email.setCustomValidity("");
    };
    
});
<html>
<body>
  <form action="submit.php" method="POST">
  
        <div class="user_data">
            <label for="name">Name:&nbsp;</label><input id="name" name="name" type="text" required></input><br>
        </div>
        <div class="user_data">
            <label for="surname">Last name:&nbsp;</label><input id="surname" name="surname" type="text" required></input><br>
        </div>
        <div class="user_data">
            <label for="email">Email:&nbsp;</label><input id="email" name="email" type="email" required></input><br>
        </div>
    </form>
</body>
</html>
wayta
  • 35
  • 7
  • 3
    Your live demo throws error. Try providing a [mcve] (which you should only need one of your three validation routines to make it minimal, and you'll need one of your HTML inputs to make it reproducible). Also tell us what input you expect to pass the test which doesn't. – Quentin Mar 30 '21 at 16:08
  • https://stackoverflow.com/a/23544789/5407229 This answer seems related to the error in the live demo. You need the html in order for the demo to work. – Joshua Swain Mar 30 '21 at 16:12
  • you can provide html by pasting it in a proper window – tarkh Mar 30 '21 at 16:15

1 Answers1

4

You are trying to comparing your input with in_name

it should be in_name.value

change pt1.test(in_name) to pt1.test(in_name.value)

Rahul Khunt
  • 643
  • 5
  • 6