JavaScript settings login
JavaScript is a commonly used programming language, usually used for interactive effects and dynamic data processing on Web pages. In web applications, login is a very important function, which involves issues such as the security and privacy protection of user information. Today we will explore how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users and logging out, etc.
Verify user input
Before setting up the login function, we need to ensure that the information entered by the user is legal and valid, such as user name and password. To validate user input, we can use methods such as regular expressions, form validation, and server-side authentication.
Regular expression is a language for matching patterns, which can help us check whether the input is valid or well-formatted. For example, a simple regular expression can check whether the input is a valid email address:
function validateEmail(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());
}Form validation is another method of validating user input. It can check the input by setting rules and error prompts. effectiveness. For example, we can use HTML and JavaScript code to validate a login form, ensuring that both the username and password are required and that the username contains at least 6 characters:
<form id="loginForm" onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required minlength="6"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Log in">
</form>
<script>
function validateForm() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
if (username.length < 6) {
document.getElementById("username").setCustomValidity("Username must contain at least 6 characters");
return false;
} else {
document.getElementById("username").setCustomValidity("");
}
if (password.length < 8) {
document.getElementById("password").setCustomValidity("Password must contain at least 8 characters");
return false;
} else {
document.getElementById("password").setCustomValidity("");
}
return true;
}
</script>Server-side authentication is the last line of defense. It ensures that the information entered by the user is legal and valid as it verifies that the username and password match the records in the database. For example, we can use Node.js and the Express framework to implement server-side authentication:
app.post('/login', function(req, res) {
const username = req.body.username;
const password = req.body.password;
if(username === 'admin' && password === 'admin') {
res.status(200).send('Login successful');
} else {
res.status(401).send('Invalid username or password');
}
});Handling login requests
Once the user has entered a valid username and password, and the verification has passed, we need Use it to handle login requests and create sessions. A session is an interaction method between the server and the client, which allows the server to maintain contact with the client for a certain period of time and save the user's status and information on the server.
In web applications, we can use cookies and sessions to create and manage user sessions. Among them, a cookie is a small text file that can be stored in the user's computer by the web browser and sent to the server the next time it visits the website; the session is a server-side data structure that can store and manage user status and information.
For example, we can use JavaScript code to create a session and store user information:
function login(username, password) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/login');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
const user = response.user;
const sessionId = response.sessionId;
// Save user information and sessionId in cookies
document.cookie = `user=${user}`;
document.cookie = `sessionId=${sessionId}`;
// Redirect user to home page
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
};
const data = JSON.stringify({ username: username, password: password });
xhr.send(data);
}In this example, we use the XMLHttpRequest object to send a POST request, sending the username and password to the server authenticating. If the login is successful, the server will return the user information and session ID, which we can store in cookies. We then redirect the user to the home page, maintaining the user session through the information in the cookie.
Remember User
After the user logs in, we can improve the user experience by remembering the username and password, and allow the user to log in automatically the next time they visit the website. This can be achieved by storing username and password in cookies.
For example, we can use JavaScript code to remember a user's username and password:
function rememberMe() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (document.getElementById('rememberMe').checked) {
// Save username and password in cookies for 30 days
const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString();
document.cookie = `username=${username}; expires=${expires};`;
document.cookie = `password=${password}; expires=${expires};`;
} else {
// Remove username and password from cookies
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
document.cookie = "password=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
}
}In this example, we use a checkbox to represent the "Remember Me" option. If the user checks this option, we store the username and password in a cookie and set the expiration time to 30 days. If the user cancels this option, we will delete the username and password from the cookie.
Log out
Finally, we need to provide a convenient way for users to log out to avoid accidental or illegal use of the user's account. Logging out requires destroying the user session and clearing the information in cookies.
For example, we can use JavaScript code to log out:
function logout() {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/logout');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
// Remove user information and sessionId from cookies
document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
document.cookie = 'sessionId=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
// Redirect user to login page
window.location.href = '/login';
} else {
alert('Logout failed');
}
};
const sessionId = getCookie('sessionId');
const data = JSON.stringify({ sessionId: sessionId });
xhr.send(data);
}In this example, we use the XMLHttpRequest object to send a POST request and send the session ID to the server. The server will destroy the user session and return a success status code. We will then remove the user information and session ID from the cookie and redirect the user to the login page.
Conclusion
In this article, we explored how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users, and logging out. Login is a very important function in web applications, which involves important issues such as the security and privacy protection of user information. By using technologies such as JavaScript and server-side authentication, we can ensure that the information entered by users is legal and valid, and improve user experience and security.
The above is the detailed content of JavaScript settings login. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1378
52
What is useEffect? How do you use it to perform side effects?
Mar 19, 2025 pm 03:58 PM
The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.
How does currying work in JavaScript, and what are its benefits?
Mar 18, 2025 pm 01:45 PM
The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read
What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?
Mar 18, 2025 pm 01:44 PM
Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.
How does the React reconciliation algorithm work?
Mar 18, 2025 pm 01:58 PM
The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159
What is useContext? How do you use it to share state between components?
Mar 19, 2025 pm 03:59 PM
The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.
How do you connect React components to the Redux store using connect()?
Mar 21, 2025 pm 06:23 PM
Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.
How do you prevent default behavior in event handlers?
Mar 19, 2025 pm 04:10 PM
Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.
What are the advantages and disadvantages of controlled and uncontrolled components?
Mar 19, 2025 pm 04:16 PM
The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.


