仅验证表单中的可见字段

时间:2017-09-06 05:18:35

标签: javascript jquery angularjs

我正在验证一张表格。如果未输入必填字段,则会返回alert。工作正常。

现在我通过添加 ng-class 隐藏了一些表单字段,当我点击提交时我不想验证隐藏的字段我只想验证那些不是拥有hidden class

这些是我的输入:

    <section  ng-class="{'hidden':true}">
            <input class="required" ng-model="currentData.name" />      
    </section>
    <section ng-class="{'hidden':true}">
            <input  class="required" ng-model="currentData.id"/>    
    </section>
    <section>
        <input class="required" type="text" ng-model='currentData.age'/>    
    </section>

    <section ng-class="{'hidden':true}">
        <input class="required" ng-model='currentData.gender'/> 
    </section>

    <section>
        <input class="required" ng-model='currentData.description'/>    
    </section>


Here am validating my fields :

    $form.find('input.required').each(function() {

                var $this = $(this)
                if ($this.val().trim() == '') {
                    alert("enter required fields")
                }       
            })

I have added `:visible`  its working good.But that wont be a proper solution I guess.Because if there are multiple tabs which is not having `hidden class`means, it will validate only current tab user currently viewing.

    $form.find('input.required:visible').each(function() {

                var $this = $(this)
                if ($this.val().trim() == '') {
                    alert("enter required fields")
                }       
            })

还有其他建议吗?

2 个答案:

答案 0 :(得分:1)

$('form').find('input.required').parent('*:not(".hidden")').each(function() {
        var $this = $(this)
        if ($this.val().trim() == '') {
            alert("enter required fields")
        }
    })

假设$('form')<form></form>

否则应该是这样的 $('#form')

<div id="form"></div>

答案 1 :(得分:0)

得到解决方案:

$form.find('section').not(".hidden").closest('input.required').each(function() {})

我刚刚更改了元素顺序。