email validation

Whing Dela Cruz
Whing Dela Cruz used Ask the Experts™
on
Hi experts, due to some issue,I want to change the input type from type="email" to  type="text". Would it be possible to do this and maintain the way I validate the email base on the code shown below? Thank you!

<!DOCTYPE html>
<html lang="en">
<head>
    <title>email validator</title>
<body>
<form>
<input type="email" placeholder="email" name="email" required>
<input type="submit" value="Create Account">
</form>

<script>
var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            alert("Success ");
            this.setCustomValidity('');
            return true;
        }
    });
})
</script>
</body>
</html>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Tahir QureshiSystem Analyst
Commented:
can you try the below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title>email validator</title>
<body>
<form>
<input type="text" placeholder="email" name="email" required>
<input type="submit" value="Create Account">
</form>

<script>
var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=text]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            alert("Success ");
            this.setCustomValidity('');
            return true; 
        }
    });
})
</script> 
</body>
</html>

Open in new window

Author

Commented:
Hello Tahir, its not working. no validation happen when I press enter...
Prakash SamariyaIT Professional
Top Expert 2015
Commented:
@Whing Dela Cruz, your given code is working fine for me with minor change. I just added jQuery CDN which was missing! in your example!

Could you please describe more if not works?
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

This sample may help you !
<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }    
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="email">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

Open in new window

Author

Commented:
Hi SniperCode, Please note that I am not using Php. I prefer JavaScript or VbScript solution. Thanks!

Author

Commented:
Hello prakash, you commented "I just added jQuery CDN which was missing! in your example!" I didn't see your solutions. What does your comments all about?
Here is your code updated :
<!DOCTYPE html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

<html lang="en">
<head>
    <title>email validator</title>
<body>
<form>
<input type="text" placeholder="email" name="email" required>
<input type="submit" value="Create Account">
</form>

<script>
var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=text]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            alert("Success ");
            this.setCustomValidity('');
            return true; 
        }
    });
})
</script> 
</body>
</html>

Open in new window

Prakash was right ! You just have to add this
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

Open in new window

in your code and it will work !
Prakash SamariyaIT Professional
Top Expert 2015

Commented:

Hello prakash, you commented "I just added jQuery CDN which was missing! in your example!" I didn't see your solutions. What does your comments all about?
You are trying to use jQuery in your javascript <script> tag
$(document).ready(function(){
...

Open in new window

But to use it we need to include jQuery library into HTML page!  

From your HTML you have given in your question, does not included jQuery, so your working code also not working!

Please add jQuery library and test it! You can include jQuery library in HTML in two ways
- You can download jQuery library and then, add it to your HTML page. Download jQuery
- Include library by referencying to jQuery CDN (content delivery network) into your HTML page.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Open in new window

Author

Commented:
Thank you guys, more power to you all. It helps me a lot!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial