我一直在寻找我的表单验证在过去3个小时内无效的原因,似乎无法找到答案。
我在HTML,表单id,onclick事件中有外部脚本文件。我错过了什么?有人可以帮忙吗?
HTML
<script src="registration.js"></script>
<form id="registration">
<fieldset>
<legend>Individual/Company Details</legend>
<br />
<label class="error">Fields with an asterisk (*) are required</label>
<br />
<br />
<label>First Name *: </label>
<br />
<input id="firstname" name="firstname" type="text" />
<br />
<label>Last Name *: </label>
<br />
<input id="lastname" name="lastname" type="text" />
<br />
<label>Username *: (alpha-numeric characters only) </label>
<br />
<input id="username" name="username" type="text" />
<br />
<label>Password *: (8 characters with 2 characters being numbers) </label>
<br />
<input id="password" name="password" type="password" />
<br />
<label>Date of Birth: (dd/mm/yyyy) </label>
<br />
<input id="dob" name="dob" type="text" />
<br />
<label>Gender: </label>
<br />
<br />
<input id="gender" class="radio" name="gender" type="radio" value="Male" />Male
<input class="radio" name="gender" type="radio" value="Female" />Female
<input class="radio" name="gender" type="radio" value="Other" />Other
<br />
<br />
<label>E-mail *: </label>
<br />
<input id="email" name="email" type="text" />
<br />
<label>Address *: (alpha-numeric characters only)</label>
<br />
<textarea id="address" name="address" cols="20" rows="10"></textarea>
<br />
</fieldset>
<fieldset>
<legend>Membership</legend>
<br />
<label>Membership Type *: </label>
<select id="membership" name="membership">
<option value= "" selected= "selected">(select membership type)</option>
<option value= "gold">Gold</option>
<option value= "silver">Silver</option>
<option value= "mithril">Mithril</option>
</select>
<br />
<br />
</fieldset>
<p class="buttons">
<label>
<input class= "button" type= "reset" value= "Clear" />
<input class= "button" type= "submit" value= "Submit" onclick= "validateForm();" />
</label>
</p>
</form>
registration.js
// JavaScript Document
// Conditions are checked upon submission of form and error messages are displayed
function validateForm() {
var error_message = "";
// Different functions for validation of different input
error_message += validateFirstName();
error_message += validateLastName();
error_message += validateUserName();
error_message += validatePassword();
error_message += validateDoB();
error_message += validateGender();
error_message += validateEmail();
error_message += validateAddress();
error_message += validateMembership();
error_message += validateDuration();
if (error_message != "") {
alert("Some fields have invalid entry:\n" + error_message);
return false;
}
return true;
}
// Validation of First Name
function validateFirstName() {
var error = "";
var nonletters = /[^a-zA-Z]+/;
if (document.forms["registration"]["firstname"].value.length == 0) // condition is checked if field is left blank
{
registration.firstname.focus();
error = "First name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["firstname"].value.match(nonletters)) // condition is checked if field is alphabetical characters only
{
registration.firstname.focus();
registration.firstname.select();
error = "Alphabetical characters only for first name \n"; // error message is displayed if field is not alphabetical characters only
}
return error;
}
// Validation of Last Name
function validateLastName() {
var error = "";
var nonletters = /[^a-zA-Z]+/;
if (document.forms["registration"]["lastname"].value.length == 0) // condition is checked if field is left blank
{
registration.lastname.focus();
error = "Last name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["lastname"].value.match(nonletters)) // condition is checked if field is alphabetical characters only
{
registration.lastname.focus();
registration.lastname.select();
error = "Alphabetical characters only for last name \n"; // error message is displayed if field is not alphabetical characters only
}
return error;
}
// Validation of User Name
function validateUserName() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
if (document.forms["registration"]["username"].value.length == 0) // condition is checked if field is left blank
{
registration.username.focus();
error = "User name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["username"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.username.focus();
registration.username.select();
error = "Alpha-numeric characters only for user name \n"; // error message is displayed if field is not alpha-numeric characters only
}
return error;
}
// Validation of Password
function validatePassword() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
var numbers = /(?=(.*\d){2})/;
if (document.forms["registration"]["password"].value.length == 0) // condition is checked if field is left blank
{
registration.password.focus();
error = "Password is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["password"].value.length != 8) // condition is checked if password is not eight characters
{
registration.password.focus();
registration.password.select();
error = "Password of 8 characters is required \n"; // error message is displayed if password is not eight characters
} else if (document.forms["registration"]["password"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.password.focus();
registration.password.select();
error = "Alpha-numeric characters only for password \n"; // error message is displayed if field is not alpha-numeric characters only
} else if (!(document.forms["registration"]["password"].value.match(numbers))) // condition is checked if field has at least two numbers
{
registration.password.focus();
registration.password.select();
error = "Password must contain at least 2 numbers \n"; // error message is displayed if field does not have at least two numbers
}
return error;
}
// Validation of Date of Birth
function validateDoB() {
var error = "";
var dob = document.forms["registration"]["dob"].value;
var validdob = /\d{2}\/\d{2}\/\d{4}/;
if (dob.length == 0) // condition is checked if field is left blank
{
error = ""; // no error message is displayed if field is blank
} else if (!(dob.match(validdob))) // condition is checked if field is in correct format
{
registration.dob.focus();
registration.dob.select();
error = "Please enter date of birth in valid format \n"; // error message is displayed if field is in incorrect format
}
return error;
}
// Validation of Gender
function validateGender() {
var error = "";
if (document.forms["registration"]["gender"].value.unchecked) // condition is checked if field is left blank
{
error = ""; // no error message is displayed if field is blank
}
return error;
}
// Validation of Email Address and format validity
function validateEmail() {
var error = "";
var email = document.forms["registration"]["email"].value;
var emailformat = /\w+([\.-]?\w{1})*@\w{1}([\.-]?\w+)*(\.\w{1})+/
if (email.length == 0) // condition is checked if field is left blank
{
registration.email.focus();
error = "Email address is required \n"; // error message is displayed if field is blank
} else if (!(email.match(emailformat))) // condition is checked if field is in correct format
{
registration.email.focus();
registration.email.select();
error = "Please enter a valid email address \n"; // error message is displayed if invalid email address entered
}
return error;
}
// Validation of Address
function validateAddress() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
if (document.forms["registration"]["address"].value.length == 0) // condition is checked if field is left blank
{
registration.address.focus();
error = "An address is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["address"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.address.focus();
registration.address.select();
error = "Alpha-numeric characters only for address \n"; // error message is displayed if field is not alpha-numeric characters only
}
return error;
}
// Validation of Membership Type
function validateMembership() {
var error = "";
if (document.forms["registration"]["membership"].value == "default") // condition is checked if field is left as default
{
registration.membership.focus();
error = "Membership type must be selected \n"; // error message is displayed if field is not selected
}
return error;
}
// Validation of Membership Duration
function validateDuration() {
var error = "";
if (document.forms["registration"]["duration"].value == "default") // condition is checked if field is left as default
{
registration.duration.focus();
error = "Membership duration must be selected \n"; // error message is displayed if field is not selected
}
return error;
}
答案 0 :(得分:2)
删除
<input class= "button" type= "submit" value= "Submit" onclick= "validateForm();" />
使用
document.getElementById("registration").addEventListener("submit", validateForm);
在你的js文件中,试试这个:
function validateForm(event) {
var error_message = "";
// Different functions for validation of different input
error_message += validateFirstName();
error_message += validateLastName();
error_message += validateUserName();
error_message += validatePassword();
error_message += validateDoB();
error_message += validateGender();
error_message += validateEmail();
error_message += validateAddress();
error_message += validateMembership();
error_message += validateDuration();
if (error_message != "") {
alert("Some fields have invalid entry:\n" + error_message);
event.preventDefault();
}
}
// Validation of First Name
function validateFirstName() {
var error = "";
var nonletters = /[^a-zA-Z]+/;
if (document.forms["registration"]["firstname"].value.length == 0) // condition is checked if field is left blank
{
registration.firstname.focus();
error = "First name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["firstname"].value.match(nonletters)) // condition is checked if field is alphabetical characters only
{
registration.firstname.focus();
registration.firstname.select();
error = "Alphabetical characters only for first name \n"; // error message is displayed if field is not alphabetical characters only
}
return error;
}
// Validation of Last Name
function validateLastName() {
var error = "";
var nonletters = /[^a-zA-Z]+/;
if (document.forms["registration"]["lastname"].value.length == 0) // condition is checked if field is left blank
{
registration.lastname.focus();
error = "Last name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["lastname"].value.match(nonletters)) // condition is checked if field is alphabetical characters only
{
registration.lastname.focus();
registration.lastname.select();
error = "Alphabetical characters only for last name \n"; // error message is displayed if field is not alphabetical characters only
}
return error;
}
// Validation of User Name
function validateUserName() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
if (document.forms["registration"]["username"].value.length == 0) // condition is checked if field is left blank
{
registration.username.focus();
error = "User name is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["username"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.username.focus();
registration.username.select();
error = "Alpha-numeric characters only for user name \n"; // error message is displayed if field is not alpha-numeric characters only
}
return error;
}
// Validation of Password
function validatePassword() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
var numbers = /(?=(.*\d){2})/;
if (document.forms["registration"]["password"].value.length == 0) // condition is checked if field is left blank
{
registration.password.focus();
error = "Password is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["password"].value.length != 8) // condition is checked if password is not eight characters
{
registration.password.focus();
registration.password.select();
error = "Password of 8 characters is required \n"; // error message is displayed if password is not eight characters
} else if (document.forms["registration"]["password"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.password.focus();
registration.password.select();
error = "Alpha-numeric characters only for password \n"; // error message is displayed if field is not alpha-numeric characters only
} else if (!(document.forms["registration"]["password"].value.match(numbers))) // condition is checked if field has at least two numbers
{
registration.password.focus();
registration.password.select();
error = "Password must contain at least 2 numbers \n"; // error message is displayed if field does not have at least two numbers
}
return error;
}
// Validation of Date of Birth
function validateDoB() {
var error = "";
var dob = document.forms["registration"]["dob"].value;
var validdob = /\d{2}\/\d{2}\/\d{4}/;
if (dob.length == 0) // condition is checked if field is left blank
{
error = ""; // no error message is displayed if field is blank
} else if (!(dob.match(validdob))) // condition is checked if field is in correct format
{
registration.dob.focus();
registration.dob.select();
error = "Please enter date of birth in valid format \n"; // error message is displayed if field is in incorrect format
}
return error;
}
// Validation of Gender
function validateGender() {
var error = "";
if (document.forms["registration"]["gender"].value.unchecked) // condition is checked if field is left blank
{
error = ""; // no error message is displayed if field is blank
}
return error;
}
// Validation of Email Address and format validity
function validateEmail() {
var error = "";
var email = document.forms["registration"]["email"].value;
var emailformat = /\w+([\.-]?\w{1})*@\w{1}([\.-]?\w+)*(\.\w{1})+/
if (email.length == 0) // condition is checked if field is left blank
{
registration.email.focus();
error = "Email address is required \n"; // error message is displayed if field is blank
} else if (!(email.match(emailformat))) // condition is checked if field is in correct format
{
registration.email.focus();
registration.email.select();
error = "Please enter a valid email address \n"; // error message is displayed if invalid email address entered
}
return error;
}
// Validation of Address
function validateAddress() {
var error = "";
var nonalphanum = /[^0-9a-zA-Z]+/;
if (document.forms["registration"]["address"].value.length == 0) // condition is checked if field is left blank
{
registration.address.focus();
error = "An address is required \n"; // error message is displayed if field is blank
} else if (document.forms["registration"]["address"].value.match(nonalphanum)) // condition is checked if field is alpha-numeric characters only
{
registration.address.focus();
registration.address.select();
error = "Alpha-numeric characters only for address \n"; // error message is displayed if field is not alpha-numeric characters only
}
return error;
}
// Validation of Membership Type
function validateMembership() {
var error = "";
if (document.forms["registration"]["membership"].value == "default") // condition is checked if field is left as default
{
registration.membership.focus();
error = "Membership type must be selected \n"; // error message is displayed if field is not selected
}
return error;
}
// Validation of Membership Duration
function validateDuration() {
var error = "";
if (document.forms["registration"]["duration"].value == "default") // condition is checked if field is left as default
{
registration.duration.focus();
error = "Membership duration must be selected \n"; // error message is displayed if field is not selected
}
return error;
}
答案 1 :(得分:0)
虽然创建表单并使用HTML5进行验证(参见此article)要容易得多,但代码现在可以正常运行; console.log()是一个不错的调试工具。我注释掉了调用“validateDuration()”,因为成员资格持续时间没有相应的HTML表单字段。
确保提交有效表单有助于在表单元素onsubmit="return validateForm()"
中编码,这样如果表单无法验证函数的返回值为false,则会依次返回,从而阻止表单被提交
在表单验证方面,您可以停止操作并关注无效字段并显示错误消息,也可以显示所有错误的清单。我认为做前者更加用户友好,所以我相应地更改了代码。
// registration.js contents:
var d = document;
d.f = d.forms;
d.g = d.getElementById;
var error_message = "";
function doErrorMsg(obj,em){
obj.innerHTML="<span>Invalid, as follows:</span><br>\n" + em;
obj.style.visibility="visible";
}
function validateForm(){
if (error_message = validateFirstName()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateLastName()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateUserName()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validatePassword()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateDoB()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateGender()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateEmail()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateAddress()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
else
if (error_message = validateMembership()) {
doErrorMsg( d.g("errormsg"),error_message);
return false;
}
//error_message += validateDuration();
if (error_message == ""){
return true;
}
}// end validateForm
// Validate First Name
function validateFirstName() {
var nonletters = /[^a-zA-Z]+/;
var fname = d.f["registration"]["firstname"];
if ( fname.value.length == 0 ) {
fname.focus();
fname.select();
return("First name is required<BR>\n");
}
else
if (fname.value.match(nonletters)) {
fname.focus();
fname.select();
return("Alphabetical characters only for first name \n");
}
return(""); // no error
}// end validateFirstName
// Validate Last Name
function validateLastName(){
var nonletters = /[^a-zA-Z]+/;
var lname = d.f["registration"]["lastname"];
if (lname.value.length == 0) {
lname.focus();
lname.select();
return("Last name is required<BR>\n");
}
else
if (lname.value.match(nonletters)) {
lname.focus();
lname.select();
return("Alphabetical characters only for last name<BR>\n");
}
return(""); // no error
}// end validate last name
// Validation of User Name
function validateUserName(){
var nonalphanum = /[^0-9a-zA-Z]+/;
var uname = d.f["registration"]["username"];
if (uname.value.length == 0) {
uname.focus();
uname.select();
return("User name is required<BR>\n");
}
else
if (uname.value.match(nonalphanum)) {
uname.focus();
uname.select();
return("Alpha-numeric characters only for user name<BR>\n");
}
return(""); // no error
}// end validate user name
// Validate Password
function validatePassword(){
var nonalphanum = /[^0-9a-zA-Z]+/;
var numbers = /(?=(.*\d){2})/;
var pword = d.f["registration"]["password"];
if (pword.value.length == 0) {
pword.focus();
pword.select();
return("Password is required<BR>\n");
}
else
if (pword.value.length != 8) {
pword.focus();
pword.select();
return("Password of 8 characters is required <BR>\n");
}
else
if ( pword.value.match(nonalphanum) ) {
pword.focus();
pword.select();
return("Alpha-numeric characters only for password<BR>\n");
}
else
if ( !pword.value.match( numbers ) ) {
pword.focus();
pword.select();
return("Password must contain at least 2 numbers<BR>\n");
}
return(""); // no error
}// end validate password
// Validate DoB
function validateDoB(){
var dob = d.f["registration"]["dob"];
var validdob = /\d{2}\/\d{2}\/\d{4}/;
if (dob.value.length == 0) {
return(""); // no error if blank field
}
else
if ( !( dob.value.match( validdob ) ) ) {
dob.focus();
dob.select();
return("Please enter date of birth in valid format<BR>\n");
}
return(""); // no error
}// end validate DoB
// Validate Gender
function validateGender(){
var gender = d.f["registration"]["gender"];
if (gender.value.unchecked) {
// no error if blank field
}
return(""); // no error
}
// Validate Email
function validateEmail() {
var email = d.f["registration"]["email"];
var emailformat = /\w+([\.-]?\w{1})*@\w{1}([\.-]?\w+)*(\.\w{1})+/
if (email.value.length == 0) {
email.focus();
email.select();
return("Email address is required<BR>\n");
}
else
if ( !( email.value.match( emailformat ) ) ){
email.focus();
email.select();
return("Please enter a valid email address<BR>\n"); }
return(""); // no error
}// end validate email
// Validate Address
function validateAddress(){
var alphanum = /[0-9a-zA-Z ,.\n\r]+/;
var addr = d.f["registration"]["address"];
if (addr.value.length == 0) {
addr.focus();
addr.select();
return("An address is required<BR>\n");
}
else
if (addr.value.match( alphanum ) ) {
return(""); // no error
}
else
{
addr.focus();
addr.select();
return("Alpha-numeric characters only for address <BR>\n");
}
}// end validate address
// Validatr Membership Type
function validateMembership(){
var membership = d.f["registration"]["membership"];
if ( membership.value == "default"){
membership.focus();
return("Membership type must be selected<BR>\n");
}
return(""); // no error
}// end validate membership type
// Validate (Membership) Duration
function validateDuration(){
var mDuration = d.f["registration"]["duration"];
if (mDuration.value == "default") {
mDuration.focus();
return("Membership duration must be selected <BR>\n");
}
return(""); // no error
}
submit.onclick = function() {
error_message = "";
d.g("errormsg").innerHTML="";
d.g("errormsg").style.visibility="hidden";
};
#errormsg {
color: #f00;
position:absolute;
top: 10vh;
left: 42vw;
width: 20vw;
padding: 10px;
border: 2px solid #000;
box-shadow: 2px 2px 6px #777;
visibility:hidden;
}
span {
color:black;
}
.button {
background:#000;
color:#0f0;
}
<div id="errormsg"></div>
<form id= "registration" onsubmit="return validateForm();">
<fieldset>
<legend>Individual/Company Details</legend>
<br />
<label class= "error">Fields with an asterisk (*) are required</label>
<br />
<br />
<label>First Name *: </label>
<br />
<input id= "firstname" name= "firstname" type= "text" />
<br />
<label>Last Name *: </label>
<br />
<input id= "lastname" name= "lastname" type= "text" />
<br />
<label>Username *: (alpha-numeric characters only) </label>
<br />
<input id= "username" name= "username" type= "text" />
<br />
<label>Password *: (8 characters with 2 characters being numbers) </label>
<br />
<input id= "password" name= "password" type= "password" />
<br />
<label>Date of Birth: (dd/mm/yyyy) </label>
<br />
<input id= "dob" name= "dob" type= "text" />
<br />
<label>Gender: </label>
<br />
<br />
<input id= "gender" class= "radio" name= "gender" type= "radio" value= "Male" />Male
<input class= "radio" name= "gender" type= "radio" value= "Female" />Female
<!--input class= "radio" name= "gender" type= "radio" value= "Other" />Other
<br /-->
<br />
<label>E-mail *: </label>
<br />
<input id= "email" name= "email" type= "text" />
<br />
<label>Address *: (alpha-numeric characters only)</label>
<br />
<textarea id= "address" name= "address" cols= "20" rows= "10"></textarea>
<br />
</fieldset>
<fieldset>
<legend>Membership</legend>
<br />
<label>Membership Type *: </label>
<select id= "membership" name= "membership">
<option value= "default" selected= "selected">(select membership type)</option>
<option value= "gold">Gold</option>
<option value= "silver">Silver</option>
<option value= "mithril">Mithril</option>
</select>
<br />
<br />
</fieldset>
<p class= "buttons">
<label>
<input class= "button" type= "reset" value= "Clear" />
<input id="submit" name="submit" class= "button" type= "submit" value= "Submit" />
</label>
</p>
</form>
注意,我更改了地址字段的验证,以便用户不会因为用户习惯做的而输入逗号,空格或句点而受到惩罚。
应谨慎使用评论,否则他们可能会模糊注意到重要的项目。
我使用了一些简写来减少代码的冗长程度。此外,我消除了各种验证函数中的变量错误,而是返回附加到error_message的相应消息。
此外,alert()已消失,取而代之的是网页上的反馈,这对用户来说更方便。请注意,在这种情况下,提交按钮的onclick属性对于删除旧的错误消息非常有用。
顺便说一句,如果OP希望容纳那些不认同传统男性或女性的用户,可能希望从Facebook获取提示,而不是拥有“其他”类别(参见here)