- This topic is empty.
-
AuthorPosts
-
July 9, 2017 at 8:05 am #8992
David Hoang
KeymasterES6 sample
const validateEmail=(email)=> /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
February 27, 2018 at 4:56 am #8979David Hoang
Keymaster<input type="email" class="form-control" required="required" placeholder="Email Address" name="Email" id="Email" autocomplete="Email"> <button class="btn-1 shadow-0 full-width" type="button" id="register">Register account</button>
$("#register").click(function(){ var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var Email = $("#Email").val(); var x = rea.test(Email); if (!x) { alert('Type Your valid Email'); return false; } </script>
February 28, 2018 at 7:18 am #8993David Hoang
KeymasterHere’s a simple regex that would just check for the basic format of an email e.g.,
X@Y.C
:\S+@\S+\.\S+
May 28, 2018 at 11:02 am #8994David Hoang
KeymasterThis question is more dificult to answer than seems at first sight.
There were loads of people around the world looking for “the regex to rule them all” but the truth is that there are tones of email providers.
What’s the problem? Well, “a_z%@gmail.com cannot exists but it may exists an address like that through another provider “a__z@provider.com.
Why?
According to the RFC:
https://en.wikipedia.org/wiki/Email_address#RFC_specification.I’ll take an excerpt to facilitate the lecture:
The local-part of the email address may use any of these ASCII characters: - uppercase and lowercase Latin letters A to Z and a to z; - digits 0 to 9; - special characters !#$%&'*+-/=?^_`{|}~; - dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6] Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often. - space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); - comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.
So, i can own an email address like that:
A__z/J0hn.sm{it!}h_comment@example.com.co
If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it’s fair valid.
Imagine my frustration at not being able to register anywhere checked with those regex!!
The only one who really can validate an email address is the provider of the email address.
How to deal with, so?
It doesn’t matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type=”email” that is running near to RFC, little chance to fail.
HTML5 input type=”email” info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.htmlFor example, this is an RFC valid email:
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
But the html5 validation will tell you that the text before @ must not contain ” or () chars for example, which is actually incorrect.
Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.
A good practice while doing this is the “enter your e-mail again” input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title “is this your current e-mail?”, then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a “yes, submit” button.
July 18, 2018 at 5:15 am #8980David Hoang
KeymasterHere is a solution that works and includes validation/notification fuctionality in a form:
You can run it at this link
JAVASCRIPT
(function() { 'use strict'; window.addEventListener('load', function() { var form = document.getElementById('needs-validation'); form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); } form.classList.add('was-validated'); event.preventDefault(); }, false); }, false); })();
HTML
<p class='title'> <b>Email validation</b> <hr size="30px;"> </p> <br> <form id="needs-validation" novalidate> <p class='form_text'>Try it out!</p> <div class="form-row"> <div class="col-12"> <input type="email" class="form-control" placeholder="Email Address" required> <div class="invalid-feedback"> Please enter a valid email address. </div> </div> <div class="row"> <div class="col-12"> <button type="submit" class="btn btn-default btn-block">Sign up now </button> </div> </div> </form>
July 22, 2018 at 5:53 am #8981David Hoang
KeymasterI wrote a JavaScript email validator which is fully compatile with PHP’s
filter_var($value, FILTER_VALIDATE_EMAIL)
implementation.https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js
import validateEmail from 'filter-validate-email' const value = '...' const result = validateEmail(value)
is equivalent to:
<?php $value = '...'; $result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
February 24, 2019 at 3:19 am #8982David Hoang
KeymasterHere’s how I do it. I’m using match() to check for the standard email pattern and I’m adding a class to the input text to notify the user accordingly. Hope that helps!
$(document).ready(function(){ $('#submit').on('click', function(){ var email = $('#email').val(); var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (email.match(pat)){ $('#email') .addClass('input-valid'); return false; } else { $('#email') .addClass('input-error') .val(''); return false; } }); });
.input-error { border: 1px solid red; color: red; } .input-valid { border: 1px solid green; color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="text" id="email" placeholder="name@service.xx" class=""> <input type="submit" id="submit" value="Send"/> </form>
March 1, 2019 at 11:27 am #8972David Hoang
KeymasterThere is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(
EmailValidator.validate
) and kind(EmailValidator.validateKind
).The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.
export class EmailValidator { /** * @param {string} email * @return {string} * @throws {Error} */ static validate(email) { email = this.prepareEmail(email); const isValid = this.validateKind(email); if (isValid) return email; throw new Error(`Got invalid email: ${email}.`); } /** * @param {string} email * @return {boolean} */ static validateKind(email) { email = this.prepareEmail(email); const regex = this.getRegex(); return regex.test(email); } /** * @return {RegExp} * @private */ static getRegex() { return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; } /** * @param {string} email * @return {string} * @private */ static prepareEmail(email) { return String(email).toLowerCase(); } }
To validate an email you can follow these ways:
// First way. try { EmailValidator.validate('balovbohdan@gmail.com'); } catch (e) { console.error(e.message); }
// Second way. const email = 'balovbohdan@gmail.com'; const isValid = EmailValidator.validateKind(email); if (isValid) console.log(`Email is valid: ${email}.`); else console.log(`Email is invalid: ${email}.`);
April 23, 2019 at 3:43 am #8973David Hoang
KeymasterI am using this function
/** * @param {*} email */ export const validateEmail = email => { return new RegExp(/[\w-]+@([\w-]+\.)+[\w-]+/gm).test(email); };
April 25, 2019 at 9:46 am #8995David Hoang
KeymasterGeneral email regex (RFC 5322 Official Standard): https://emailregex.com/
JavaScript:
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
June 5, 2019 at 5:14 am #8983David Hoang
KeymasterIf you want something a human can read and maintain, I would recommend Masala Parser (I’m one of the creators of it).
import {C,Streams} from '@masala/parser' const illegalCharset = ' @\u00A0\n\t'; const extendedIllegalCharset = illegalCharset + '.'; // Assume 'nicolas@internal.masala.co.uk' export function simpleEmail() { return C.charNotIn(illegalCharset).rep() // 'nicolas' .then(C.char('@')) .then(subDns()) //'internal.masala.co.' .then(C.charNotIn(extendedIllegalCharset).rep()) //'uk' .eos(); // Must be end of the char stream } // x@internal.masala.co.uk => extract 'internal.masala.co.' function subDns() { return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep() } function validateEmail(email:string) { console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted())); } validateEmail('nicolas@internal.masala.co.uk'); // True validateEmail('nz@co.'); // False, trailing "."
If you want to accept the ultimate ugly email version, you can add in quotes in the first part:
function inQuote() { return C.char('"') .then(C.notChar('"').rep()) .then(C.char('"')) } function allEmail() { return inQuote().or(C.charNotIn(illegalCharset)) .rep() // repeat (inQuote or anyCharacter) .then(C.char('@')) .then(subDns()) .then(C.charNotIn(extendedIllegalCharset).rep()) .eos() // Must be end of the character stream // Create a structure .map(function (characters) { return ({ email: characters.join('') }); }); }
'"nicolas""love-quotes"@masala.co.uk'
is officially valid, but should it be in your system?At least with Masala, you give yourself a chance to understand it. And so for the next year, colleague.
September 17, 2019 at 10:00 am #8996David Hoang
KeymasterUse the browser/runtime to handle parsing the input by prepending a protocol and pass it to the
URL
API, trapping any errors and check the resultingusername
andhostname
properties of the result. It will handle basically all transformations and possibilities (punycode of character sets, etc). This only establishes that the input is parsable, not that is valid–that is only possible through checking if the destination machine receives messages for that alias. This provides a close (imo reasonable) guess though, and can be expanded to be more specific and realistic if you’re comfortable both maintaining it and also risking invalid rejections. (Note it doesn’t attempt to address IPv4 or IPv6 addresses, simply the broad range of customer-facing scenarios using a domain.)function validEmail(email=''){ var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i; email = email.trim(); try{ url = new URL('http://'+email); $0 = `${url.username}@${url.hostname}`; isValid = emailPatternInput.test( email ); if(!isValid) throw 'invalid email pattern on input:' + email; isValid = emailPatternUrl.test( $0 ); if(!isValid) throw 'invalid email pattern on url:' + $0; console.log(`email looks legit "${email}" checking url-parts: "${$0 === email ? '-SAME-':$0}"`); }catch(err){ console.error(`probably not an email address: "${email}"`, err); }; return isValid; } ['user+this@ã¯ã˜ã‚よã†.ã¿ã‚“ãª', 'stuff@things', 'user+that@host.com', 'Jean+François@anydomain.museum','هيا@×™×ללה', '试@例å.测试.مثال.آزمایشی', 'not@@really', 'no'].forEach(email=>console.log(validEmail(email), email));
This is the both the simplest and most generally permissive example I can come up with. Please edit it in cases where it can be made to be more accurate while maintain its simplicity and reasonable generally permissive validity.
Also see MDN URL docs URL, window.URL and Nodejs for URL APIs.
November 18, 2019 at 5:22 am #8984David Hoang
KeymasterThese will work with the top used emails(they match exactly the rules of each one).
Gmail
/^[a-z]((?!\.\.)([a-z\.])){4,28}[a-z0-9]@gmail.com$/i
Yahoo
/^[a-z]((?!\.\.)([\w\.])){3,30}[\w]@yahoo.com$/i
Outlook/Hotmail
/[a-z]((?!\.\.)([\w\.])){0,62}[\w]@(outlook.com|hotmail.com)$/i
November 8, 2020 at 2:09 am #8985David Hoang
Keymaster// Html form call function name at submit button <form name="form1" action="#"> <input type='text' name='text1'/> <input type="submit" name="submit" value="Submit" onclick="ValidateEmail(document.form1.text1)"/> </from> // Write the function name ValidateEmail below <script> function ValidateEmail(inputText) { var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; if(inputText.value.match(mailformat)) { alert("Valid email address!"); document.form1.text1.focus(); return true; } else { alert("You have entered an invalid email address!"); document.form1.text1.focus(); return false; } } </script>
April 14, 2021 at 4:42 am #8986David Hoang
KeymasterYet another perfect regexp for email validation
/^([^\s\@])+\@(([^\s\@\.])+\.)+([^\s\.]{2,})+$/
You can test it here https://regex101.com/r/FV3pUI/2
-
AuthorPosts
- You must be logged in to reply to this topic.