Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively validating HTML input elements

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

}
like image 323
dimlee Avatar asked May 20 '15 20:05

dimlee


People also ask

How do you input validation in HTML?

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.

How can you specify that an external input element belongs to a particular form?

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.


1 Answers

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"))
like image 137
AmmarCSE Avatar answered Oct 10 '22 21:10

AmmarCSE