I have written the following recursive input validator and it works for me. Is there a better way to visit each dom element and check if it is an input field and validate it?
function formValidator(parent)
{
//base case no children
if( parent.children().length == 0)
return
//recurse through each childs' child
parent.children().each(function(){
formValidator($(this));
/**
* Work : check if this node is an input node
*/
if($(this).is("input"))
{
var type = $(this).attr('type');
if(type =="text")
//do work bro
}
});//end for each
}
The simplest HTML validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.
In HTML5, you can use the form attribute: A form-associated element is, by default, associated with its ancestor form element, but may have a form attribute specified to override this.
If by better you mean less verbose, this is equivalent functionally
parent.find('*').each(function(){
/**
* Work : check if this node is an input node
*/
if($(this).is("input"))
{
var type = $(this).attr('type');
if(type =="text")
//do work bro
}
});//end for each
Notice that there is no need for recursion here because
parent.find('*')
uses the *(all-selector). This will get all children and nested children.
Update
To improve performance, you can refactor above to
parent.find('input[type="text"]').each(function(){
var type = $(this).attr('type');
//if(type =="text")
//above no longer needed
});//end for each
This will get all nested input
elements so you won't have to even check for
if($(this).is("input"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With