我想使用JavaScript验证表单。
为此,我创建了一个函数validate
,当我单击“提交”按钮时该函数应该起作用。
该消息应使用alert
函数显示,但运行时未显示任何警报。
function validate() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var cpassword = document.getElementById('cpassword').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var cpasswordRGEX = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$/i;
var passwordRGEX = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$/i;
var emailRGEX = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var firstnameRGEX = /^[a-z ,.'-]+$/i;
var lastnameRGEX = /^[a-z ,.'-]+$/i;
var firstnameresult = firstnameRGEX.test(firstname);
var lastnameresult = lastnameRGEX.test(lastname);
var passwordResult = passwordRGEX.test(password);
var emailResult = emailRGEX.test(email);
var cpasswordresult = cpasswordRGEX.test(cpassword);
alert("Email:" + emailResult + ", password:" + passwordResult + ", cpassword: "+ cpasswordresult + "firstname: " + firstnameresult + ",lastname:" + lastnameresult);
return false;
}
<form onsubmit="validate()">
<center>
<h1>Dashboard</h1>
<br>
<label>First Name:</label>
<input type="text" name="fname" placeholder="First Name" class="email" id="firstname" />
<br>
<label>Last Name:</label>
<input type="text" name="lname" placeholder="Last Name" class="email" id="lastname" />
<br>
<label>Username:</label>
<input type="text" name="username" placeholder="Username" class="email" />
<br>
<label>Gender:</label>
<select name="" id="" class="email">
<option>Male</option>
<option>Female</option>
</select>
<br>
<label>Age:</label>
<input type="number" name="age" value="" placeholder="18" class="email">
<br>
<label>Blood Group:</label>
<select name="bloodgroup" id="" class="email">
<option>A</option>
<option>A-</option>
<option>B+</option>
<option>B-</option>
<option>O+</option>
<option>O-</option>
<option>AB+</option>
<option>AB-</option>
</select>
<br>
<label>Email:</label>
<input type="text" name="email" value="email" onFocus="field_focus(this, 'email');" onblur="field_blur(this,
'email');" class="email" id="email" />
<br>
<label>Password:</label>
<input type="password" name="password" value="email" onFocus="field_focus(this, 'email');" onblur="field_blur(this,
'email');" class="email" id="password" />
<br>
<label>Confirm Password:</label>
<input type="password" name="cpassword" value="email" onFocus="field_focus(this, 'email');" onblur="field_blur(this,
'email');" class="email" id="cpassword" />
<a href="#">
<div id="btn2">Sign Up</div>
</a>
<!-- End Btn2 -->
<input type="submit">
</form>