当前位置:网站首页>JS mailbox regular expression

JS mailbox regular expression

2022-06-23 20:40:00 It workers

How to verify whether the mailbox expression is correct ?

Use Regular expressions Maybe the best way , You can see some examples here ( stay chrome Test on the console ).

function validateEmail(email) {
    const re = /^(([^<>()\[\]\.,;:\[email protected]"]+(\.[^<>()\[\]\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/;
    return re.test(String(email).toLowerCase());
}

The following is acceptable unicode Examples of regular expressions for :

const re = /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i;

But remember , We should not rely solely on JavaScript verification . You can easily disable JavaScript. It is also necessary to verify on the server side .

Here is an example :

function validateEmail(email) {
  const re = /^(([^<>()[\]\.,;:\[email protected]\"]+(\.[^<>()[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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,}))$/;
  return re.test(email);
}

function validate() {
  const $result = $("#result");
  const email = $("#email").val();
  $result.text("");

  if (validateEmail(email)) {
    $result.text(email + " is valid :)");
    $result.css("color", "green");
  } else {
    $result.text(email + " is not valid :(");
    $result.css("color", "red");
  }
  return false;
}

$("#validate").on("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate'>Validate!</button>
</form>

<h2 id='result'></h2>
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112291835095973.html