HTML 表单验证:用户名、密码、手机号、邮箱
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form action="submit.php" method="post" onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" minlength="6" maxlength="12" pattern="[a-zA-Z][a-zA-Z0-9]*" required><br><br>
<p><label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8" maxlength="20" required><br><br></p>
<p><label for="phone">Phone Number:</label>
<input type="text" id="phone" name="phone" pattern="(13|15|18)\d{9}" required><br><br></p>
<p><label for="email">Email:</label>
<input type="email" id="email" name="email" pattern="^[^\s@]+@[^\s@]+\.[^\s@]+$" required><br><br></p>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var usernamePattern = /^[a-zA-Z][a-zA-Z0-9]{5,11}$/;
var phonePattern = /^(13|15|18)\d{9}$/;
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!usernamePattern.test(username)) {
alert("Invalid username. Username must be 6-12 characters long and can only contain letters and numbers. It cannot start with a number.");
return false;
}
if (password.length < 8 || password.length > 20) {
alert("Invalid password. Password must be 8-20 characters long.");
return false;
}
if (!phonePattern.test(phone)) {
alert("Invalid phone number. Phone number must start with 13, 15, or 18 and be 11 digits long.");
return false;
}
if (!emailPattern.test(email)) {
alert("Invalid email address. Email address must have only one @ and cannot start or end with @.");
return false;
}
return true;
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/p51p 著作权归作者所有。请勿转载和采集!