I'm new to jQuery and was wondering how to use it to validate email addresses.
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
You can use regular old javascript for that:
You can create your own function
I would use the jQuery validation plugin for a few reasons.
You validated, ok great, now what? You need to display the error, handle erasing it when it is valid, displaying how many errors total perhaps? There are lots of things it can handle for you, no need to re-invent the wheel.
Also, another huge benefit is it's hosted on a CDN, the current version at the time of this answer can be found here: http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx This means faster load times for the client.
If you have a basic form, just make the input type of email:
<input type="email" required>
This will work for browsers that use HTML5 attributes and then you do not even need JS. Just using email validation even with some of the scripts above will not do much since:
some@email.com so@em.co my@fakemail.net
etc... Will all validate as "real" emails. So you would be better off ensuring that the user has to enter their email address twice to make sure that they put the same one in. But to guarantee that the email address is real would be very difficult but very interesting to see if there was a way. But if you are just making sure that it is an email, stick to the HTML5 input.
FIDDLE EXAMPLE
This works in FireFox and Chrome. It may not work in Internet Explorer... But internet explorer sucks. So then there's that...
: www.htmldrive.net
Source:htmldrive.com
Landed here.....ended up here: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
...which provided the following regex:
...which I found thanks to a note on the jQuery Validation plugin readme: https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue
So, the updated version of @Fabian's answer would be:
Hope that helps