我正在尝试从Javascript-Coder.com实现可以找到here的JavaScript表单验证脚本。
我有它在表单上的元素工作,但我想知道如何使它与数组一起工作。具体来说,我在网页here上有一个表单,用户可以在其中添加行。然后我有以下表格:
<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>
但是,如果用户在表单的顶部添加第二行,则脚本仅验证第一行中的电子邮件地址,我想知道如何验证添加到第一行的每一行形式也是如此。
其他信息
根据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>";
}
答案 0 :(得分:1)
您可以在每个字段上添加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>
验证添加。 阵列和颜色的东西有点微不足道,你应该展示你在这里做了多少努力。只有当你看到某人的意志时,才有意义。
答案 1 :(得分:0)
我已经决定添加其他的衣服,因为还有其他一些我想提及的关于debuging的事情。
至于你提到它的错误:
<div id="booking" style="font-size:16px;margin-bottom:10px;padding:5px">Please add the number of people
为什么会这样?
如果你仔细观察它已经为id分配了预订值,但你也为html表单分配了相同的id,这会产生冲突,因为javascript不知道你的意思是哪一个。
<强>通知书强>
- 你在debuging时总是分配东西,这意味着你必须自己运行上面的脚本,如果运行正常然后嵌入你的应用程序没有那么你知道100%存在冲突。
- 你提到了一个创建问题的特定功能(你是对的),然后你必须进入该功能并发出一个警报('Hello there whatever!');从最顶端开始一次在一条线上,一旦警报没有加速,那么你知道哪条线有问题。然后你警告这一行上的变量,看看他们是否有他们应该拥有的价值......很可能这个价值不具备必须拥有的值,而你的问题已经很小了。
现在,照顾身份证,他们必须是独一无二的!如果你看到我的例子,我会在结尾处为它们分配一个增加的索引
id="someElement"+(id++);
对不起,如果这太难看了......但是错误的方式调试可能会比这更痛苦(有一些关于调试的神教程!)。