简体   繁体   中英

How to validate email input in jQuery?

I am not using the form tag.

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

This is the 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");
        }
    });
});

Normally Chrome forces your email input to be valid, before it allow you to submit.

How can I do this with just jQuery Ajax, where no form tag or button is present?

If you don't want to use form, then the other way i suggest would be to use a Regular Expression to test the email value you received. Use javascript's RegExp.

    $(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
            }
     })

Got the Regex from answer of this stackoverflow question.

You can just use vanilla Javascript's checkValidity() :

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

You do not need jQuery for email validation. As long as you use the <input type="email"> attribute, the form submission will fail if the syntax is malformed.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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