<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> label { display: inline-block; width: 80px; text-align: right; } span { color: red; } </style></head><body> <!-- onsubmit的默认事件是触发action --> <form action="hi.html" onsubmit=""> <p><label for="username">用户名:</label><input type="text" id="username" /><span id="usernameWarn"></span></p> <p><label for="password">密码:</label><input type="password" id="password" /><span id="passwordWarn"></span></p> <p><label for="repassword">确认密码:</label><input type="password" id="repassword" /><span id="repasswordWarn"></span></p> <!-- button的点击事件的默认事件是触发form表单的onsubmit --> <p><button onclick="registerValidate()">注册</button></p> </form></body><script> var usernameEle = document.getElementById("username"); var usernameWarnEle = document.getElementById("usernameWarn"); var usernameRegExp = /^(\[email protected]\w+\.\w+)|(1[3458]\d{9})$/; var passwordEle = document.getElementById("password"); var passwordWarnEle = document.getElementById("passwordWarn"); var passwordRegExp = /^[0-9a-zA-Z]{6,12}$/; var repasswordEle = document.getElementById("repassword"); var repasswordWarnEle = document.getElementById("repasswordWarn"); function registerValidate() { //清空所有验证 usernameWarnEle.innerHTML = ""; passwordWarnEle.innerHTML = ""; repasswordWarnEle.innerHTML = ""; //验证用户名 if (usernameEle.value == "") { usernameWarnEle.innerHTML = "用户名不能为空!"; } else if (!usernameRegExp.test(usernameEle.value)) { usernameWarnEle.innerHTML = "用户名只能是邮箱或手机号码!"; } //验证密码 if (passwordEle.value == "") { passwordWarnEle.innerHTML = "密码不能为空!"; } else if (!passwordRegExp.test(passwordEle.value)) { passwordWarnEle.innerHTML = "密码只能由6到12位的英文字母或数字组成!"; } //确认密码 if (repasswordEle.value == "") { repasswordWarnEle.innerHTML = "密码不能为空!"; } else if (passwordEle.value != repasswordEle.value) { repasswordWarnEle.innerHTML = "输入的密码不一致!"; } }</script></html>
时间: 2024-10-05 10:26:44