gpt4 book ai didi

javascript - 如何在表单中只接受两种电子邮件域?

转载 作者:行者123 更新时间:2023-12-03 04:53:40 25 4
gpt4 key购买 nike

我有一个表单,其中一个输入字段要求用户输入他们的电子邮件。但是,我只想接受@gmail.com和@outlook.com,但我的代码似乎只接受@outlook.com。任何人都可以对我的代码提出一些建议吗?

    $( "#email" ).change(function() {
if (this.value.length <= 0 ) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You need to enter your email";
} else if (this.value.length > 200) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "The email is too big.";
} else if ((this.value.search('@outlook.com') == -1 || this.value.search('@gmail.com') == -1) || (this.value.length != this.value.search('@outlook.com')+12 ||this.value.length != this.value.search('@gmail.com')+10)) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You must enter your Gmail or Outlook email";
} else {
email=1;
$(this).removeClass( 'error_class' );
$(this).addClass( 'success_class' );
document.getElementById("emailError").innerHTML = "";
}
});

最佳答案

使用正则表达式 /\@(gmail|outlook){1}\.com$/i ->

  • \@ 应包含@
  • (gmail|outlook) 只能出现一次 gmail 或 Outlook
  • .com$ .com 和结尾
  • i -> 标记不区分大小写

$( "#email" ).change(function() {
if (this.value.length <= 0 ) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You need to enter your email";
} else if (this.value.length > 200) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "The email is too big.";
} else if (!/\@(gmail|outlook)\.com$/i.test(this.value)) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You must enter your Gmail or Outlook email";
} else {
email=1;
$(this).removeClass( 'error_class' );
$(this).addClass( 'success_class' );
document.getElementById("emailError").innerHTML = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="email" name="email" type="email" />
<div id="emailError"></div>

关于javascript - 如何在表单中只接受两种电子邮件域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com