目标:使用JS实现对用户名和密码进行正则表达式判断,用户名和密码正确时,进行网页跳转。
用户名、密码的正则表达式检验
HTML代码:
<button type="submit" id="login-btn" /*onclick="login();alidateLogin();"*/ onblur="checkusernameandpassword()">登录</button>
JS代码:
/* 使用正则表达式验证登录时的用户名和密码是否合法 */
function checkusernameandpassword() {
const username = document.querySelector('#login-username').value;
const password = document.querySelector('#login-password').value;
const usernameRegex = /^[a-zA-Z0-9_-]{5,15}$/;
const passwordRegex = /^[a-zA-Z0-9_-]{5,15}$/;
if (usernameRegex.test(username) && passwordRegex.test(password)) {
console.log('用户名和密码合法');
return true;
} else {
console.log('用户名或密码不合法');
return false;
}
}
JS实现一个按钮绑定两个onclick事件
HTML代码:
<button type="submit" id="login-btn" /*onclick="login();alidateLogin();"*/ onblur="checkusernameandpassword()">登录</button>
JS代码:
/* 一个按钮绑定两个事件 */
var btn = document.getElementById("login-btn");
btn.addEventListener("click", login);
btn.addEventListener("click", validateLogin);
模拟登录实现:
HTML代码:
<button type="submit" id="login-btn" /*onclick="login();alidateLogin();"*/ onblur="checkusernameandpassword()">登录</button>
JS代码:
/* 登录时验证用户名和密码 */
function validateLogin() {
const username = document.querySelector('#login-username').value;
const password = document.querySelector('#login-password').value;
if (username === 'admin' && password === '123456') {
console.log('登录成功');
window.location.href = 'index.html';
return true;
} else {
console.log('登录失败');
return false;
}
}