Reputation: 893
I have a form which is dynamically built from an xml file and looks like this with all the meaningless info stripped out:
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" />
}
Now i have a validation script i use for client side
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);
}
Then i run the following on the form:
onSubmit="return validate()
Now that works fine for a static form but on my dynamic form im not sure how to make it run the validation for every loop.
I have a similar situation for my server side validation and i use the following to access each one for the file size and type validation:
$file_size = $_FILES[$form_field_name]['size'][$key];
But im not sure how to do a similar thing for the javascript as the current script runs onSubmit and im not sure how to access each value client side.
Upvotes: 0
Views: 47
Reputation: 6202
First of all, you want you IDs to be unique. Assuming $popup_item is a good varname string:
foreach($xml->config->popup as $popup_item)
{
<input id="<?php echo $popup_name ; ?>" name="<?php echo $popup_name ; ?>" type="text" value="" />
etc.
But then do another loop to generate your validation code:
foreach($xml->config->popup as $popup_item)
{
var image_value = document.getElementById("<?php echo $popup_name ; ?>").value;
etc.
Upvotes: 1