Home > other >  How can i add specific email validation for html
How can i add specific email validation for html

Time:11-02

I would like to know how to only allow @gmail.com and @yahoo.com for my email validation in html. I know about the <input type="email" validation but that would allow emails in any format and I only want those two to be accepted. How do I do it??

CodePudding user response:

The only way is RegExp

  1. If you are using a framework (angular/react/vue) they have there own(compatible third party) libraries to handle form validation.
  2. If you are using plain JS you can add onchange event with your input and test the input with desired regex or before submitting the form you can test the input.

Regex you will need

/^[a-z][a-z0-9_.]*@(gmail|yahoo).com$/gm

More about Regex with Javascript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

CodePudding user response:

Ok, it is not the best way of achieving this, for best way use it at backend, with PHP email validation filter.

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/master.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
</script>
</head>
<body>
<form id="emailForm" action="" method="post">
<label for="email">E-mail</label><br>
<input id="email" type="email" name="email" placeholder="Please enter your 
email" value="">
<button onclick="validate();" type="button" name="button">Submit</button>
</form>
</body>
</html>

Inline javascript, you can carry it later, keep it under html for testing purposes.

<script type="text/javascript">
function validate(){
var email = $('#email').val();

if (email.length == 0) {
  window.alert("you didn't enter an email");
}

if (!email.includes('@')) {
  window.alert("you mail is unvalid");
}

var emailHost = email.substr((-1)*(email.length - email.indexOf('@') - 1));

var allowedDomains = ["gmail.com","hotmail.com","yahoo.com"];

var inAllowed = false;
for(i=0;i<allowedDomains.length;i  ){
  if (allowedDomains[i] == emailHost) {
    inAllowed = true;
  }
}

if (!inAllowed) {
  window.alert("your e-mail hosting not supported");
}else { //submit form here
  window.alert("success");
  $('#emailForm').submit();
}

}
</script>

And back end get email from $_POST if using php

<?php

var_dump($_POST);

?>
  • Related