点击注册的时候,渲染出来,验证码是自动获取出来的
html:
<div class="div1">
用户名<input type="text" id="yhm"><span id="span1"></span><br>
密码<input type="password" id="mm"><span id="span2"></span><br>
Email<input type="email" id="ema"><span id="span3"></span><br>
手机号<input type="text" id="sjh"><span id="span4"></span><br>
验证码<input type="text" id="yzm" maxlength="4"><span id="span5"></span><br>
<button id="btn">注册</button>
</div>
<p id="p1"></p>
script:
<script>
// 用户名验证
document.getElementById("yhm").addEventListener("blur", function () {
var username = this.value;
var spanElement = document.getElementById("span1");
var usernameRegex = /^[a-zA-Z0-9]{3,6}$/;
if (usernameRegex.test(username)) {
spanElement.innerHTML = '√';
} else {
spanElement.innerHTML = '×';
}
});
// 密码验证
document.getElementById("mm").addEventListener("blur", function () {
var password = this.value;
var spanElement = document.getElementById("span2");
if (password.length >= 6 && password.length <= 16) {
spanElement.innerHTML = '√';
} else {
spanElement.innerHTML = '×';
}
});
// Email验证
document.getElementById("ema").addEventListener("blur", function () {
var email = this.value;
var spanElement = document.getElementById("span3");
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailRegex.test(email)) {
spanElement.innerHTML = '√';
} else {
spanElement.innerHTML = '×';
}
});
// 手机号验证
document.getElementById("sjh").addEventListener("blur", function () {
var phoneNumber = this.value;
var spanElement = document.getElementById("span4");
var phoneRegex = /^1\d{10}$/;
if (phoneRegex.test(phoneNumber)) {
spanElement.innerHTML = '√';
} else {
spanElement.innerHTML = '×';
}
});
// 生成验证码
function generateCaptcha() {
var captcha = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 4; i++) {
captcha += characters.charAt(Math.floor(Math.random() * characters.length));
}
return captcha;
}
// 显示验证码
document.getElementById("yzm").value = generateCaptcha();
// 注册按钮点击事件
document.getElementById("btn").addEventListener("click", function () {
var p1Element = document.getElementById("p1");
var yhmInput = document.getElementById("yhm").value;
var mmInput = document.getElementById("mm").value;
var emaInput = document.getElementById("ema").value;
var sjhInput = document.getElementById("sjh").value;
var yzmInput = document.getElementById("yzm").value;
p1Element.innerHTML = "用户名:" + yhmInput + "<br>" +
"密码:" + mmInput + "<br>" +
"Email:" + emaInput + "<br>" +
"手机号:" + sjhInput + "<br>" +
"验证码:" + yzmInput;
});