Validations in angularJS

Sandy V
Sandy V used Ask the Experts™
on
Is there a way to set two fields combined as required field in AngularJS, let's say you have two text fields Product & Order & i need to make sure that atleast one of the field is populated
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Take a look at the ng-required directive https://docs.angularjs.org/api/ng/directive/ngRequired
<input ng-required="expression">

Open in new window


where expression is an expression that checks your model values

<input ng-required="!(model.Product.length || model.Order.length)">

Open in new window


In your controller code
...
 $scope.model = {
    Product: '',
    Order: '',
    ...
 }

Open in new window

Sandy VDeveloper

Author

Commented:
Here Product & Order are 2 different input fields. Where should i put the ng-required directive?? i thought the only way to achieve this is using a custom directive
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
The ng-required goes on the fields that need to be validated. So if either Product or Order MUST be filled in then both of them have the ng-required with the same rule (as per my earlier post)

When the validation runs the ng-validate expressions are evaulated and based on the values the expressions return will determine if the field fails or passes validation.

In the example above the ng-validate expression is running against the state of two fields in the model (Product and Order) if both of these have a .length of 0 then the validation fails otherwise it passes - so if anything is entered into either Product or Order both fields will pass validation.
Sandy VDeveloper

Author

Commented:
Perfect, thanks for the explanation
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial