用js实现 // 3, 有以下表单, 验证用户名, 密码, 手机号 // 用户名只包含数字,字母,下划线, 且长度不小于6位 // 密码长度在8到16位 // 手机号要合法 // 保存到cookie中
时间: 2024-01-04 18:04:57 浏览: 33
可以使用正则表达式来验证用户名、密码和手机号是否合法。具体实现如下:
```javascript
// 获取表单元素
const usernameInput = document.querySelector('#username');
const passwordInput = document.querySelector('#password');
const phoneInput = document.querySelector('#phone');
// 监听表单提交事件
document.querySelector('#form').addEventListener('submit', function(event) {
// 阻止表单默认提交行为
event.preventDefault();
// 验证用户名
const username = usernameInput.value.trim();
if (!/^\w{6,}$/.test(username)) {
alert('用户名不合法');
return;
}
// 验证密码
const password = passwordInput.value.trim();
if (password.length < 8 || password.length > 16) {
alert('密码长度应在8到16位之间');
return;
}
// 验证手机号
const phone = phoneInput.value.trim();
if (!/^1\d{10}$/.test(phone)) {
alert('手机号不合法');
return;
}
// 保存到cookie中
document.cookie = `username=${username}; max-age=3600`;
document.cookie = `password=${password}; max-age=3600`;
document.cookie = `phone=${phone}; max-age=3600`;
// 提示保存成功
alert('保存成功');
});
```
需要注意的是,此代码中使用了 ES6 的模板字符串语法,以方便拼接字符串。同时,为了避免用户输入的值包含空格等不必要的字符,我们使用了 `trim()` 方法来去除首尾空格。最后,为了方便测试,我们设置了 `max-age` 属性来限制 cookie 的有效期为1小时。