Javascript 如何让表单验证程序脚本与数组一起工作?
我正在尝试从JavaScript-Coder.com实现可以找到的JavaScript表单验证脚本 我让它用于表单上的元素,但我想知道如何让它用于数组。具体来说,我在网页上有一个表单,用户可以向其中添加行。那么我有以下表格:Javascript 如何让表单验证程序脚本与数组一起工作?,javascript,arrays,forms,validation,Javascript,Arrays,Forms,Validation,我正在尝试从JavaScript-Coder.com实现可以找到的JavaScript表单验证脚本 我让它用于表单上的元素,但我想知道如何让它用于数组。具体来说,我在网页上有一个表单,用户可以向其中添加行。那么我有以下表格: <form method="post" name="booking" id="booking" action="bookingengine.php"> <fieldset> <h2>Waged/Organisati
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset>
<h2>Waged/Organisation Rate</h2>
<p>
<input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<fieldset>
<h2>Unwaged Rate</h2>
<p>
<input type="text" name="name2[]" id="name2">
<input type="text" name="email2[]" id="email2">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<p><input type="submit" name="submit" id="submit" value="Submit and proceed to payment page" class="submit-button" /></p>
</form>
下注/组织费率
添加人
未固定利率
添加人
当前表单验证程序脚本如下所示:
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("booking");
frmvalidator.addValidation("email[]","req","Please enter a valid email address");
frmvalidator.addValidation("email[]","email","Please enter a valid email address");
</script>
var frmvalidator=新验证器(“记账”);
frmvalidator.addValidation(“电子邮件[]”,“请求”,“请输入有效的电子邮件地址”);
frmvalidator.addValidation(“电子邮件[]”,“电子邮件”,“请输入有效的电子邮件地址”);
但是,如果用户在表单顶部添加第二行,脚本只验证第一行中的电子邮件地址,我想知道如何让它也验证添加到表单中的每一行
其他信息
按照Melsi的建议,用于生成表单和处理验证的脚本已经完全重写。下面由Melsi提供的答案包括我要求的以下功能(其中大部分也在原始脚本中):
//validate-name
box=document.getElementById(caller).name.charAt(0);
if(box=='n'){
if((document.getElementById(caller).value)=='Name')
{
alert('Please enter your name')
document.getElementById('message').innerHTML="<span>Please enter your name</span>";
//put focus back again if you like
document.getElementById(caller).focus();
return;
}
}
//if code comes here = validation success
document.getElementById(caller).style.backgroundColor = '#F5FEC1';
document.getElementById('message').innerHTML="<span style="+dbq+"background-color: #A3BB00"+ dbq+">Thanks!</span>";
}
<div id="booking" style="font-size:16px;margin-bottom:10px;padding:5px">Please add the number of people
//验证名称
box=document.getElementById(调用者).name.charAt(0);
如果(框=='n'){
if((document.getElementById(caller.value)=='Name')
{
警报('请输入您的姓名')
document.getElementById('message').innerHTML=“请输入您的姓名”;
//如果你愿意的话,把焦点放回去
document.getElementById(调用者).focus();
返回;
}
}
//如果代码出现在这里=验证成功
document.getElementById(调用者).style.backgroundColor='#F5FEC1';
document.getElementById('message').innerHTML=“谢谢!”;
}
您可以在每个字段上添加onchange事件,即使是在动态字段中,它们也会在更改时将验证器称为sson,以便用户立即知道它是否是有效入口
============编辑的部分,这里有一些代码被更好的版本替换=====
我匆忙地写了这段代码,应用了颜色示例,也添加了新行示例,也添加了删除,也应用了焦点上的空框以及所有其他问题
<html>
<head>
<script type="text/javascript">
/**
A dynamic name is assigned to a new field created.
*/
var id=0;
var dbq="\"";
/************************* addRow function end ******************************************/
function addRow(count)
{
/**
Decide what fieldset is going to host the row
*/
var myFieldset='fieldset2';
var section='2';
if(count==4){
myFieldset='fieldset1';
var organisationID = id++;
var positionID = id++;
var section=''
}
/**
Create ids
*/
divID = id++;
nameID = id++;
emailID = id++;
/**
The row will be hosted in a div
*/
var myDiv = document.createElement("div");
myDiv.setAttribute("id", divID);
/**
Create the text boxes
*/
myDivInnerHTML=
'<input type=text name=name'+section+'[]'+' value=Name id='+nameID+
' onFocus='+dbq+'emptyTheBox('+nameID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+nameID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+nameID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=email'+section+'[]'+' value=Email id='+emailID+
' onFocus='+dbq+'emptyTheBox('+emailID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+emailID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+emailID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+'>' ;
/**
Decide if we need 4 or 2 boxes
*/
if(count==4)
myDivInnerHTML=myDivInnerHTML+
'<input type=text name=organisation'+section+'[]'+' value=Organisation id='+organisationID+
' onFocus='+dbq+'emptyTheBox('+organisationID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+organisationID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+organisationID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=position'+section+'[]'+' value=Position id='+positionID+
' onFocus='+dbq+'emptyTheBox('+positionID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+positionID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+positionID+');'+dbq+
' style='+dbq+'color:#66634F'+dbq+'>' ;
/**
Create a button to remove the row too.
*/
myDivInnerHTML=myDivInnerHTML+
'<input type=button class="remove" value="Remove" onClick='+dbq+'removeDiv('+divID+','+ myFieldset +');'+dbq+' >';
/**
Add the div-row to the fieldset
*/
myDiv.innerHTML = myDivInnerHTML;
document.getElementById(myFieldset).appendChild(myDiv);
}
/************************* addRow function end ******************************************/
/**
Change the color of the text being entered
*/
function changeInputColor(caller){
document.getElementById(caller).style.color = 'black';
}
/**
Remove a row on demand
*/
function removeDiv(divID, myFieldset){
myFieldset.removeChild(document.getElementById(divID));
}
/**
Empty the box on initial click
*/
function emptyTheBox(caller)
{
var val=document.getElementById(caller).value;
if(val=='Name' || val=='Email' || val=='Organisation' || val=='Position' )
document.getElementById(caller).value='';
}
/**
Display a message
*/
function echo(message)
{
document.getElementById('message').innerHTML="<h3>"+message+"</h3>";
}
/**********************Validates a single field, return false on fail************************/
function fieldValidator(caller)
{
var error='';
/**
Identify the field (if it is email, name etc) by getting the first character
which is always the same,also get its value and full name
*/
var currentFieldCategory = document.getElementById(caller).name.charAt(0);
var currentFieldValue = document.getElementById(caller).value;
var currentField = document.getElementById(caller);
/**
Check for empty value
*/
if(currentFieldValue == '')
{
echo('Please fill the data!');currentField.focus();
return 'Please fill the data!';
}
/**
Check if default value left behind
*/
if(currentFieldValue.toLowerCase()=="name" || currentFieldValue.toLowerCase()
=="email" || currentFieldValue.toLowerCase()=="organisation" ||
currentFieldValue.toLowerCase()=="position" )
{
echo('Please check you entry, default data left behind!');currentField.focus();
return 'Please check you entry, default data left behind!';
}
/**
Validate the NAME field
*/
if(currentFieldCategory=='n')
{
if(currentFieldValue.match(/^[ |'|-]/)||!(/^[a-zA-Z- ']*$/.test(currentFieldValue))
|| currentFieldValue.length<4 || currentFieldValue.length>70)
{
echo('Non valid name found!');currentField.focus();
return 'Non valid name found!';
}//inner if
}//outer if
/**
Validate a non empty EMAIL name field
*/
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("@");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Non valid email found!');currentField.focus();
return 'Non valid email found!';
}//inner if
}//outer if
/**
Validate a non empty ORGANIZATION name field
*/
if(currentFieldCategory=='o')
{
if(currentFieldValue.length<2 || currentFieldValue.length>50)
{
echo('Use at least 2 letters and less than 50 for your organisation.');
currentField.focus();
return 'Use at least 2 letters and less than 50 for your organisation.';
}//inner if
}//outer if
/**
Validate a non empty POSITON name field
*/
if(currentFieldCategory=='p')
{
if(currentFieldValue.length<7 || currentFieldValue.length>40)
{
echo('Use at least 7 letters and less than 40 to describe your position.');
currentField.focus();
return 'Use at least 7 letters and less than 40 to describe your position.';
}//inner if
}//outer if
/**
Now on success do the rest
*/
document.getElementById(caller).style.backgroundColor = '#FF9900';
document.getElementById('message').innerHTML="";
return true;
}
/*****************fieldValidator ***function ends*****************************************/
/*******************************************************************************************/
function finalValidator()
{
/**
Get the form object
*/
var myForm=document.getElementById('booking').elements;
/**
Check if the form has no rows, for now 3 indicates no rows,
BE CAREFULL it might change if more buttons added,
just alert the length to see.
*/
if(myForm.length==3)
return false;
/**
Iterate through the form for all fields
*/
for(var i = 0; i < myForm.length; i++)
{
//If it is a text field validate it
if(myForm[i].type=='text')
{
var validation = fieldValidator(myForm[i].id);
if(validation!==true)
{
echo (validation);
return false;//prevent submit
}//validation if
}//field type if
}//for loop
}//function
/*******************************************************************************************/
</script>
</head>
<body bgcolor=gray>
<div id="add-buttons"><span class="add" onclick="addRow(4);"><input type="button" class="button" value="Add Waged Person"></span><span class="add" onclick="addRow(2);"><input type="button" class="button" value="Add Unwaged Person"></span></div>
<div id="message" ></div>
<div id="form-wrap">
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset id="fieldset1">
<div class="subtitle">Waged/Organisation Rate</div>
</fieldset>
<fieldset id="fieldset2">
<div class="subtitle">Unwaged Rate</div>
</fieldset>
<!-- return finalValidator will allow submit only if fields are validated-->
<p><input type="submit" name="submit" id="submit" onClick="return finalValidator();"
value="Submit booking" class="submit-button" /></p>
</form>
</body>
</html>
/**
将为创建的新字段指定动态名称。
*/
var-id=0;
var dbq=“\”;
/*************************addRow函数结束******************************************/
函数addRow(计数)
{
/**
决定哪个字段集将作为行的宿主
*/
var myFieldset='fieldset2';
var节='2';
如果(计数=4){
myFieldset='fieldset1';
var OrganizationID=id++;
var positionID=id++;
变量节=“”
}
/**
创建ID
*/
divID=id++;
nameID=id++;
emailID=id++;
/**
该行将以div为主体
*/
var myDiv=document.createElement(“div”);
myDiv.setAttribute(“id”,divID);
/**
创建文本框
*/
MyDivinerHTML=
''+
'' ;
/**
决定我们是需要4箱还是2箱
*/
如果(计数=4)
MyDivinerHTML=MyDivinerHTML+
''+
'' ;
/**
创建一个按钮以删除该行。
*/
MyDivinerHTML=MyDivinerHTML+
'';
/**
将div行添加到字段集
*/
myDiv.innerHTML=myDivinerHTML;
document.getElementById(myFieldset).appendChild(myDiv);
}
/*************************addRow函数结束******************************************/
/**
更改正在输入的文本的颜色
*/
函数changeInputColor(调用者){
document.getElementById(调用者).style.color='black';
}
/**
根据需要删除行
*/
函数removeDiv(divID,myFieldset){
removeChild(document.getElementById(divID));
}
/**
首次单击时清空该框
*/
函数清空工具箱(调用者)
{
var val=document.getElementById(调用者).value;
如果(val='Name'| | val=='Email'| | val=='Organization'| | val=='Position')
getElementById(调用者)。值=“”;
}
/**
显示消息
*/
函数回显(消息)
{
document.getElementById('message').innerHTML=“+message+”;
}
/**********************验证单个字段,在fa上返回false
id="someElement"+(id++);