check email id valid or not without using regex in javascript
Sure! Here is an example of how you can check if an email address is valid or not in JavaScript without using regex:
function isValidEmail(email) {
var atIndex = email.indexOf('@');
var dotIndex = email.lastIndexOf('.');
// Check if '@' is present and it is not the first or last character
if (atIndex < 1 || atIndex === email.length - 1) {
return false;
}
// Check if '.' is present after '@' and it is not the first or last character
if (dotIndex - atIndex < 2 || dotIndex === email.length - 1) {
return false;
}
// Check if there are no consecutive dots
for (var i = 0; i < email.length - 1; i++) {
if (email[i] === '.' && email[i + 1] === '.') {
return false;
}
}
return true;
}
// Example usage
console.log(isValidEmail('[email protected]')); // true
console.log(isValidEmail('[email protected]')); // false
console.log(isValidEmail('test@example')); // false
console.log(isValidEmail('[email protected]')); // false
Explanation:
1. The isValidEmail
function takes an email address as input.
2. It first uses the indexOf
method to find the position of the '@' symbol in the email address and stores it in the atIndex
variable.
3. It then uses the lastIndexOf
method to find the position of the last '.' symbol in the email address and stores it in the dotIndex
variable.
4. The function performs several checks to validate the email address:
- It checks if the '@' symbol is present and it is not the first or last character in the email address.
- It checks if the '.' symbol is present after the '@' symbol and it is not the first or last character in the email address.
- It checks if there are no consecutive dots in the email address.
5. If any of these checks fail, the function returns false
, indicating that the email address is not valid.
6. If all the checks pass, the function returns true
, indicating that the email address is valid.
7. The example usage demonstrates the isValidEmail
function by passing different email addresses and printing the result to the console.
This approach checks for the basic structure and formatting of an email address without relying on regular expressions. However, it is important to note that this method may not catch all possible edge cases, and using a regular expression is generally considered a more robust solution for validating email addresses.