Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Validating email and password - JavaScript
Suppose, we have this dummy array that contains the login info of two of many users of a social networking platform ?
const array = [{
email: 'usman@gmail.com',
password: '123'
},
{
email: 'ali@gmail.com',
password: '123'
}];
We are required to write a JavaScript function that takes in an email string and a password string.
The function should return a boolean based on the fact whether or not the user exists in the database.
Example
Following is the code ?
const array = [{
email: 'usman@gmail.com',
password: '123'
}, {
email: 'ali@gmail.com',
password: '123'
}];
const matchCredentials = (email, password) => {
const match = array.find(el => {
return el.email === email && el.password === password;
});
return !!match;
};
console.log(matchCredentials('usman@gmail.com', '123'));
console.log(matchCredentials('usman@gmail.com', '1423'));
console.log(matchCredentials('ali@gmail.com', '123'));
console.log(matchCredentials('nonexistent@gmail.com', '123'));
true false true false
How It Works
The matchCredentials function uses Array.find() to search for a user object that matches both the email and password. The !!match converts the result to a boolean: true if a matching user is found, false otherwise.
Alternative Implementation
You can also use Array.some() which directly returns a boolean:
const array = [{
email: 'usman@gmail.com',
password: '123'
}, {
email: 'ali@gmail.com',
password: '123'
}];
const validateCredentials = (email, password) => {
return array.some(user => user.email === email && user.password === password);
};
console.log(validateCredentials('usman@gmail.com', '123'));
console.log(validateCredentials('wrong@gmail.com', '123'));
true false
Conclusion
Both Array.find() with boolean conversion and Array.some() can validate user credentials effectively. The some() method is more direct for boolean results, while find() is useful when you need the actual user object.
