Files
hsa/Html/apps/static/js/register.js
2025-09-24 18:12:45 +08:00

75 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

document.addEventListener('DOMContentLoaded', function() {
const registerForm = document.getElementById('register-form');
registerForm.addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm-password').value;
const u = validateLinuxUsername(username);
if (!u.ok) {
alert(u.error);
return;
}
if (password !== confirmPassword) {
alert('密码和确认密码不一致');
return;
}
fetch('/register_post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token() }}' // 如果使用 CSRF 保护
},
body: JSON.stringify({ username, email, password })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('注册成功');
window.location.href = '/login'; // 注册成功后跳转到登录页面
} else {
alert('注册失败: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('注册失败');
});
});
});
// 校验 Linux 用户名
function validateLinuxUsername(name) {
// 基本字符规则:^[a-z_][a-z0-9_-]*[$]?$
const basic = /^[a-z_][a-z0-9_-]*[$]?$/;
if (typeof name !== 'string' || name.length === 0) {
return { ok: false, error: '用户名不能为空' };
}
// 长度限制(常见系统为 <= 32
if (name.length > 32) {
return { ok: false, error: '用户名长度不能超过 32 个字符' };
}
if (!basic.test(name)) {
return {
ok: false,
error:
'用户名需以小写字母或下划线开头,仅包含小写字母、数字、下划线、连字符,允许以 $ 结尾'
};
}
// 可选:避免纯数字用户名(多数系统不推荐)
if (/^[0-9]+$/.test(name)) {
return { ok: false, error: '用户名不能为纯数字' };
}
// 可选:避免使用保留名
const reserved = new Set(['root', 'daemon', 'bin', 'sys', 'sync', 'games', 'man']);
if (reserved.has(name)) {
return { ok: false, error: '该用户名为系统保留名,请更换' };
}
return { ok: true };
}