js实现留言验证
留言验证实现方法
前端表单验证
使用JavaScript对留言表单进行基本验证,确保用户输入符合要求。以下是一个简单的实现示例:
function validateForm() {
const name = document.getElementById('name').value;
const message = document.getElementById('message').value;
if (name.trim() === '') {
alert('请输入姓名');
return false;
}
if (message.trim() === '') {
alert('留言内容不能为空');
return false;
}
if (message.length > 500) {
alert('留言内容不能超过500字');
return false;
}
return true;
}
防止XSS攻击
对用户输入进行转义处理,防止跨站脚本攻击:
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const safeMessage = escapeHtml(userInput);
验证码集成
添加图形验证码或短信验证码防止机器人提交:
// 验证验证码
function checkCaptcha(inputCode, serverCode) {
return inputCode.toLowerCase() === serverCode.toLowerCase();
}
// 示例调用
if (!checkCaptcha(userInputCaptcha, correctCaptcha)) {
alert('验证码错误');
return false;
}
后端验证
即使前端通过验证,仍需在后端进行二次验证:
// Node.js示例
app.post('/message', (req, res) => {
const { name, message, captcha } = req.body;
if (!name || !message) {
return res.status(400).json({ error: '姓名和留言不能为空' });
}
if (message.length > 500) {
return res.status(400).json({ error: '留言过长' });
}
// 进一步处理...
});
频率限制
防止用户频繁提交留言:
// 使用localStorage记录最后提交时间
const lastSubmit = localStorage.getItem('lastMessageSubmit');
const now = Date.now();
if (lastSubmit && (now - lastSubmit) < 60000) {
alert('每分钟只能提交一次留言');
return false;
}
localStorage.setItem('lastMessageSubmit', now);
敏感词过滤
实现简单的敏感词过滤功能:
const bannedWords = ['敏感词1', '敏感词2', '敏感词3'];
function containsBannedWords(text) {
return bannedWords.some(word => text.includes(word));
}
if (containsBannedWords(message)) {
alert('留言包含不允许的内容');
return false;
}






