繁体   English   中英

如何验证 jQuery 中的 email 输入?

[英]How to validate email input in jQuery?

没有使用表单标签。

<input type="email" placeholder="Email" name="email" />
<input type="password" placeholder="Password" name="password" />
<p>Submit</p>

这是 jQuery:

$(document).on("click","p",function(){
    var email = $(".inputs input[name=email]").val();
    var password = $(".inputs input[name=password]").val();
    $.ajax({
        url:"url",
        method:"POST",
        data:{email:email,password:password},
        success:function(data){
            alert("Done");
        }
    });
});

通常,Chrome 会在允许您提交之前强制您的 email 输入有效。

如何仅使用 jQuery Ajax 执行此操作,其中没有form标签或button

如果您不想使用表单,那么我建议的另一种方法是使用正则表达式来测试您收到的 email 值。 使用 javascript 的正则表达式。

    $(document).on("click","p",function(){
            var email = $(".inputs input[name=email]").val();
            var password = $(".inputs input[name=password]").val();
            var isProperEmail = new RegExp(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/).test(email);
            if(isProperEmail) {
                 //ajax Call
            } 
            else {
                 //error handler
            }
     })

从这个stackoverflow问题的答案中得到了正则表达式。

您可以只使用 vanilla Javascript 的checkValidity()

$("input[type='email']")[0].checkValidity();

对于 email 验证,您不需要 jQuery。 只要您使用<input type="email">属性,如果语法格式错误,表单提交就会失败。

 const formData = (form) => [...form.elements].filter(el => el.getAttribute('name')).reduce((acc, el) => ({...acc, [el.getAttribute('name')]: el.value }), {}); const handleSubmission = (e) => { const params = formData(e.target); fetch('/login', { method: 'POST', body: JSON.stringify(params) }).then(response => alert('Successful login')).catch((error) => console.error(`Failed to login user: ${params.email}`)); e.preventDefault(); // Remove when you want the page to navigate. }; document.forms['login'].addEventListener('submit', handleSubmission);
 <form name="login"> <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password" name="password" /> <button>Submit</button> </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM