Helen Baade
Helen Baade

Reputation: 1

How to validate email and password correctly in Javascript

in my HTML code i have this

<form name="login">
    <p> Email Address <input type="text" name="EmailAddress"> Password <input type="password" name="pword">
    <input type="button" value="Submit" onclick="ValidateUser()"></button> </p>

and in my javascript code i have this

function ValidateUser() {
   var pword= new RegExp (/^[a-zA-Z0-9]{4,100}$/)
   if (pword.test(password)) { 
      return true
   }
   else {
      alert("Incorrect Password or Username")
   }
   var email= new RegExp (/^[A-Za-z0-9_.]{2,100}+@[A-Za-z0-9.-]{2,100}+\.[A-Za-z]{2,100}$/)
   if (email.test(EmailAddress)) {
      return true
   }
   else {
      alert("Incorrect Password or Username")
   }
}

When I click the submit button with an incorrect email and password, nothing happens. The email must have at least two characters before the "@" symbol and at least two characters after the ".". The password must have a minimum of four characters, an uppercase character, a lower case character and a n

Upvotes: 0

Views: 18998

Answers (1)

Mina Atia
Mina Atia

Reputation: 790

    var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]
    {0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i     

    function validate(form){
    var email = form.email.value;
    var password = form.password.value;
    var errors = [];

     if (!ck_email.test(email)) {
      errors[errors.length] = "You must enter a valid email 
      address.";
     }

     if (password=='') {
      errors[errors.length] = "You must enter the password ";
     }

     if (errors.length > 0) {        
      reportErrors(errors);
      return false;
     }
      return true;
    }

   function reportErrors(errors){
     var msg = "Please Enter Valide Data...\n";
     for (var i = 0; i<errors.length; i++) {
     var numError = i + 1;
      msg += "\n" + numError + ". " + errors[i];
    }
     alert(msg);
    }

HTML Code You have to modify action="#"

<form method="post" action="#" onSubmit="return validate(this);" name="login">

</form>

Upvotes: 3

Related Questions