This article describes how to use JavaScript and the Prototype library to validate form fields that can be dynamically added at runtime. For example, let’s say that we have a table and the user can insert one or many new rows. Each row might contain multiple input text fields, which must be validated upon form submission.
We can’t just check all input tag fields, because there are other input fields on the page that do not belong to this table. What can we do?
In this example, each new row that is added contains an input text field to enter a person’s weight. Our validation code will verify that the user enters a numeric value in that field. We can accomplish this in two simple steps:
- Add a class attribute to each input field that contains the person’s weight.
- Use the Prototype $$ operator to get a list of input fields, then iterate over it to do each validation check.
Adding a class attribute
Here’s how to add a class attribute to each field that is dynamically added. Note that we
are using a JSTL tag to format the number when displaying the value:
<input class="Weight" type="text" size="6" value="<fmt:formatNumber value='${someObject.weight}' pattern='#,##0'/>" name="someFieldName" id="someFieldId" >
Get list of input fields based on class
Here’s how to use Prototype to get a list of input fields by a particular class name. In our case, we use this to get a list of only the fields that are used to enter a person’s weight:
function validateForm(form) { var isValid = true; //get value of all input fields with class Weight var weightFields = $$('input.Weight'); weightFields.each(function(elem){ if (isValidWeight(elem)) { null; } else { isValid = false; alert('The weight amounts must be greater than or equal to zero.'); throw $break; } }); return isValid; }
The ‘isValidWeight’ method is not shown, but it could be any validation routine that verifies that the value is a numeric value. There are two relevant points that I want to mention. First of all, we use the Prototype ‘$$’ operator to build a list of all input fields with class=’Weight’:
var weightFields = $$('input.Weight');
You can find more detail on the ‘$$’ operator at the Prototype website.
The other item to note is the use of the ‘throw $break;’ statement to break out of the loop if a field does not pass validation.
You could also use Prototype’s Enumerable.find() or reject() methods to accomplish the same thing. However, these methods scan all fields. My method breaks out of the loop on the first bad field instead of scanning all fields.
As always, happy coding!
Tags: JavaScript, Prototype