I'm working with strings in section 9 of The Complete JavaScript Course 2023: From Zero to Expert, which I purchased on Udemy.
Jonas Schmedtmann, one of Udemy's Top Instructors, demonstrates how to check the validity of email input using various methods on strings (shown in CodeSnap below).
![A CodeSnap of JavaScript string methods for converting to lowercase and getting rid of white spaces]](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mta0cxlfexunswr33de9.png)
Jonas mentioned the challenge of creating a function with checking or validating behaviour, that could return a boolean. I took on the challenge and generated three functions by prompting ChatGPT, as outlined below.
1st Function
Use a regular expression to check if the email is in the correct format
function isValidEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
}
This function takes an email as an argument and uses a regular expression to check if the email is in the correct format. The regular expression checks for the presence of an @ symbol and a ., and it also checks that the email does not contain any invalid characters.
2nd Function
To use this function, you can pass the email that you received as an input to the function and check if it is valid:
const email = 'Hello@Jonas.Io';
if (isValidEmail(email)) {
console.log('Valid email');
} else {
console.log('Invalid email');
}
This code will output Valid email, because the email is in the correct format.
3rd Function
To fix the capitalization and remove the spaces before and after the email, you can use the trim and toLowerCase methods:
const fixedEmail = email.trim().toLowerCase();
if (isValidEmail(fixedEmail)) {
console.log('Valid email');
} else {
console.log('Invalid email');
}
This code will output Valid email, because the trim method removes the leading and trailing whitespace from the email and the toLowerCase method converts the email to lowercase.
In ECMAScript 2019 (ES2019), two new string trimming methods were introduced: trimStart and trimEnd.
The trimStart method removes leading whitespace from a string, while the trimEnd method removes trailing whitespace.
Here is an example of how you can use these methods:
const str = ' Hello ';
console.log(str.trimStart()); // Output: "Hello "
console.log(str.trimEnd()); // Output: " Hello"
You can use these methods instead of the trim method if you only want to remove leading or trailing whitespace from a string.
Keep in mind that the trimStart and trimEnd methods are not supported in all browsers, so you may want to use a polyfill if you need to support older browsers.
This article was produced with the help of ChatGPT
Top comments (10)
Emails are too complex for it to be validated using regex. The most you want to check is if thereβs a
@
character and at least one character on either side of it. The only way is to actually send an email to the address.I appreciate your input and see what you mean. Like sending a test email is the only reliable way to determine if an email address is valid and can receive emails. But this might not be practical in all situations and could be time-consuming. How about using a regular expression as a basic check to help narrow down the list of potentially valid email addresses, which can make the process of sending test emails more efficient?
Since pretty much any characters are allowed inside emails, you should only check that
@
@
So:
/^(?!\s).+@.+(?<!\s)$/
.It's a lot more complicated than even that. It can't start with a dot either, for example. I would recommend against checking the whole address with regex, and instead validating the presence of one and only one @, then splitting on that and regex-validating both parts to a sufficient degree of certainty.
I mean, sure you can, but I don't see a point in doing it? Just make sure the email doesn't start or end with a space and the user will usually realize their mistake on the "we just send you an email to ______" screen.
Also, emails can have multiple
@
s.Because it still doesn't work! Like, you can check for a few obvious typos on the client side for a good user experience (e. g. Is there an @ sign) but the only good way to check for "invalid characters" is to send the test email.
For example,
incorrectly returns
false
even though it is a valid email address.So if you get bug reports because the regex is incorrect, are you really going to maintain it? I can't imagine how.
So you fall back to, "Well, not many email addresses look like that, and the regex works for most emails, so it's fine."
But then why would anyone even want such a huge and unmaintainable regex in their code if it still produces false negatives, when you can have a much smaller and much more maintainable regex which does not exclude users?
No, please don't use this so-called "regex email validation".
I can think of a few email addresses that are perfectly valid that do not match that regex. When you want to validate an email address, please do not use a hand-rolled (or even copy-n-pasted) regex.
Instead, use (Dart) pub.dev/packages/email_validator (or Perl) metacpan.org/pod/Mail::RFC822::Add..., which properly implements the RFC822 (et. seq.) address according to the rules in the RFC.
(Jokingly...) Or, cut-n-paste this one (and only this one): ex-parrot.com/~pdw/Mail-RFC822-Add.... Don't forget to remove the newlines from that 1400-char monster. :)
I greatly appreciate your input with extra resources, and making light of regex. :)
Chat GPT has led you wrong; the only reliable way to verify an email is to send an email with a verification link: if the link fires then the link works
As a bonus this also doubles as an opt-in
πβ€οΈ