【问题标题】:Want to only accept certain email address in html form只想接受 html 形式的特定电子邮件地址
【发布时间】:2021-01-06 13:08:34
【问题描述】:

我正在创建一个只接受某个电子邮件地址的表单。如果使用了错误的地址,则会出现一条消息。 我想在我的脚本中使用“.pattern!= email”之类的东西,但是我知道这个属性只能在输入中使用。我也尝试使用 .match 没有任何成功。

这是一个sn-p的形式:

<form onsubmit="return validation()">
<label for="email"> <b> Email: </b> </label>
            <input type="email" name="email" id="emailinput" placeholder="Please enter email" 
            pattern=".+@gmail.com"> <span id="message"></span>
</form>

相关脚本:

<script>
funcion validation() {
if (document.getElementById("emailinput").pattern != ".+@gmail.com") {
    document.getElementById("message").innerHTML 
    = "<em> Must be a gmail '@gmail.com' account </em>";
    return false;
else
    return true;}
</script>

【问题讨论】:

    标签: javascript html forms email


    【解决方案1】:

    @(gmail.com) 将匹配 @gmail.com 特别...

    @ 匹配 @ 符号

    有点像

    [a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S]
    你的@部分之前的部分可能工作...
    [a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S]@(gmail.com)
    

    通过函数运行您的电子邮件并返回regex.test(email),这将返回一个可在条件中使用的布尔值。

    let email = document.getElementById('email');
    let b = document.getElementById('b');
    const emailIsValid = (email) => {
      return /[\S]+@(gmail.com)/.test(email)
    }
    
    b.addEventListener('click', function() { 
      emailIsValid(email.value)?
        console.log(emailIsValid(email.value)):
        console.log(emailIsValid(email.value) + ':  ' + email.value + ' is not valid gmail address!');
      
    })
    Enter an email: &lt;input id="email"&gt; &lt;button id="b"&gt;Test It&lt;/button&gt;

    【讨论】:

    • 如果用户添加 GMAIL.COM 而不是 gmail.com 怎么办?我们怎样才能做到这一点?
    • @Ankitsethi 只需将 or => || 添加到返回 /[\S]+@(gmail.com)/.test(email) || /[\S]+@(GMAIL.COM/.test(email)
    • 谢谢,但用户也可以输入 Gmail、gMail 和类似的东西。我尝试添加 /i 以忽略大小写。但没用。
    • @Ankitsethi 试试下面的/[\S]+@(gmail.com)/i.test(email)developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    相关资源
    最近更新 更多