Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Prevent hidden form fields being validated

What is the best way of preventing hidden form fields being validated in AngularJS?

like image 226
siva636 Avatar asked Oct 01 '13 11:10

siva636


2 Answers

I initially missed the built-in ngRequired directive. There is a required tag as well, which confused me.

Now, we can use the same logic (which we used to hide the element) to set the ngRequired false.

Here is an example practical usecase: I want to ask married people the number of children they have, but, if they are not married, simply hide the field about children.

<form ng-app name="form">

    Marital status:
    <select  ng-model="maritalStatus" required>
        <option value="">Select...</option>
        <option value="M">Married</option>
        <option value="UM">Unmarried</option>
    </select>

    <div ng-show="maritalStatus == 'M'">
        Number of children: <input type="number" ng-model="children"  ng-required="maritalStatus == 'M'">
    </div>

    (for testing) Is this form correctly filled? {{form.$valid}}

</form>
like image 167
siva636 Avatar answered Oct 13 '22 20:10

siva636


You may also completely add or remove it from the DOM/form by using ng-if instead of ng-show.

<div ng-show="maritalStatus === 'M'">
    Number of children: <input type="number" ng-model="children"  ng-required="maritalStatus == 'M'">
</div>

to this

<div ng-if="maritalStatus === 'M'">
    Number of children: <input type="number" ng-model="children"  ng-required="true">
</div>
like image 20
SoEzPz Avatar answered Oct 13 '22 19:10

SoEzPz