How to properly validate an email in JavaScript using regular expressions?
Hello everyone! I'm a beginner in JavaScript and I'm writing a registration form for a website. I need to check that the user entered a valid email before sending the data to the server.
I wrote this function:
```javascript
function validateEmail(email) {
if (email.includes('@') && email.includes('.')) {
return true;
} else {
return false;
}
}
```
But it allows clearly invalid addresses, for example: "test@.com" or "user@domain" (without a dot). I understand that I need to use regular expressions, but I don't know much about them. I tried copying something like `/^\S+@\S+\.\S+$/` from the internet, but it also doesn't work for all cases — for example, it allows "a@b.c" (which seems valid, but I'm not sure).
Please advise how to write a reliable email validation.
No answers yet.
Log in to leave an answer