用原生JavaScript进行表单验证
代码如下:
<script>
let username = document.querySelector("[name=username]");
let password = document.querySelector("[name=password]");
let password_again = document.querySelector("[name=password_again]");
let submit = document.querySelector("#submit");
let message = document.querySelector("#message");
document.querySelector("#register-form").addEventListener("submit", (e)=>{
let event = e || window.event;
if(username.value == "catfish1921"){
message.innerHTML = "不好意思,这是我的专用名";
event.preventDefault();
}
if(password.value != password_again.value){
message.innerHTML = "两次密码请输入相同数值";
event.preventDefault();
}
if(username.value.length < 3 || username.value.length > 10){
message.innerHTML = "用户名保证在3-10位";
event.preventDefault();
}
})
</script>