我有一个从xml文件动态构建的表单,看起来像这样,删除了所有无意义的信息:
foreach($xml->config->popup as $popup_item)
{
<label for="fm-popup_name[]">* Popup Name:</label>
<input id="fm-popup_name[]" name="fm-popup_name[]" type="text" value="<?php echo $popup_name ; ?>" />
<label class="fm-req" for="fm-popup_desc[]">* Popup Description:</label>
<textarea rows="4" cols="50" id="fm-popup_desc[]" name="fm-popup_desc[]" /></textarea>
<label for="fm-popup_image[]">* Popup Image:</label>
<input id="fm-popup_image[]" name="fm-popup_image[]" type="file" />
}
现在我有一个用于客户端的验证脚本
function validate()
{
if(document.getElementById('fm-popup_desc').value == "" || document.getElementById('fm-popup_desc').length < 4 || document.getElementById('fm-popup_desc').value > 30){
alert( "The Description should be between 4 and 65,000 characters" );
document.getElementById('fm-popup_desc').focus() ;
return false;
}
var image_value = document.getElementById("fm-popup_image").value;
var ext_image = image_value.substring(image_value.lastIndexOf('.') + 1);
if(ext_image != "gif" && ext_image != "GIF" && ext_image != "JPEG" && ext_image != "jpeg" && ext_image != "jpg" && ext_image != "JPG" && ext_image != "png" && ext_image != "bmp"){
alert("Invalid image type, please try again using one of the following formats: gif, jpg, jpeg, bmp or png");
return false;
}
return(true);
}
然后我在表单上运行以下内容:
onSubmit="return validate()
现在它适用于静态表单但在我的动态表单上我不知道如何让它为每个循环运行验证。
我的服务器端验证有类似情况,我使用以下内容访问每个文件大小和类型验证:
$file_size = $_FILES[$form_field_name]['size'][$key];
但我不知道如何为javascript做类似的事情,因为当前脚本运行onSubmit,我不知道如何访问每个值客户端。
答案 0 :(得分:1)
首先,您希望ID是唯一的。假设$ popup_item是一个很好的varname字符串:
foreach($xml->config->popup as $popup_item)
{
<input id="<?php echo $popup_name ; ?>" name="<?php echo $popup_name ; ?>" type="text" value="" />
等
然后再做一个循环来生成验证码:
foreach($xml->config->popup as $popup_item)
{
var image_value = document.getElementById("<?php echo $popup_name ; ?>").value;
等