能给个自定义校验例子吗
好的,当然可以。我以一个常见场景举例:注册表单时,需要用户填写一个“邀请码”,但该邀请码必须由6位数字和字母组成,且不能全是数字。
HTML 部分:
<form id="myForm">
<input type="text" id="inviteCode" placeholder="请输入6位邀请码">
<span id="errorMsg" style="color:red; display:none;">邀请码格式错误</span>
<button type="submit">提交</button>
</form>
JavaScript 自定义校验逻辑:
document.getElementById('myForm').addEventListener('submit', function(event) {
// 阻止表单默认提交行为,以便我们自定义验证
event.preventDefault();
const inviteCodeInput = document.getElementById('inviteCode');
const inviteCode = inviteCodeInput.value;
const errorSpan = document.getElementById('errorMsg');
// 自定义校验规则:
// 1. 长度必须为6
// 2. 只能包含字母和数字(不包含特殊符号)
// 3. 不能全是数字(至少有一个字母)
let isValid = true;
// 规则1: 长度检查
if (inviteCode.length !== 6) {
isValid = false;
}
// 规则2: 字符类型检查(只用字母和数字)
// 使用正则表达式 /^[a-zA-Z0-9]+$/ 表示仅包含字母和数字
if (!/^[a-zA-Z0-9]+$/.test(inviteCode)) {
isValid = false;
}
// 规则3: 不能全是数字
// 使用正则 /^d+$/ 检查是否全部是数字
if (/^d+$/.test(inviteCode)) {
isValid = false;
}
// 根据校验结果显示错误或通过
if (!isValid) {
errorSpan.style.display = 'inline'; // 显示错误提示
inviteCodeInput.focus(); // 让输入框获得焦点
} else {
errorSpan.style.display = 'none'; // 隐藏错误提示
// 这里可以继续提交表单,例如:this.submit();
alert('校验通过,可以提交!');
}
});
简单解释:
- 我们拦截了表单的默认提交行为(
event.preventDefault())。 - 取出输入框的值,然后依次应用3条自定义规则。
- 如果不符合任何一条,就显示错误并阻止提交;全部通过则隐藏错误并允许提交。
复制这段代码到HTML文件中,打开页面输入试试效果。你可以根据实际需要修改规则,比如限制首字母为大写、不能包含特定字符等。