email validation

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>
Whing Dela CruzAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tahir QureshiSystem AnalystCommented:
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

0
Whing Dela CruzAuthor Commented:
Hello Tahir, its not working. no validation happen when I press enter...
0
Prakash SamariyaIT ProfessionalCommented:
@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?
0
Determine the Perfect Price for Your IT Services

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

SniperCode ShevaCommented:
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

0
Whing Dela CruzAuthor Commented:
Hi SniperCode, Please note that I am not using Php. I prefer JavaScript or VbScript solution. Thanks!
0
Whing Dela CruzAuthor 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?
0
SniperCode ShevaCommented:
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 !
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Prakash SamariyaIT ProfessionalCommented:

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

0
Whing Dela CruzAuthor Commented:
Thank you guys, more power to you all. It helps me a lot!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
CSS

From novice to tech pro — start learning today.