Recently I faced an requirement where I have to plugin ng-message validation which depends on value of other input field means if value of field A is given then only field B is mandatory. For example, if user is providing phone no then email is not mandatory else email is mandatory.
Yes we can achieve this in a very simple and straight forward way. Lets see how.
Goal: Using ng-messages validation depending upon the value of other field
Approach:
ng-messages validation simple works with html5 validation rules like required
so if we can manipulate required tag at run time depending upon our condition then we can simple switch ng-message validation ON/OFF from that field.
lets see an example:
in my case if user provide his/her phone number then his/her email is not required and even we will not show the email field.
<form name="userform">
<div id="phoneDiv">
<label>Enter phone no:</lable>
<input type="text" name="phoneno" ng-model="form.phoneNo" />
</div>
<div id="emailDiv" ng-show="!form.phoneNo">
<label>Enter email id:</lable>
<input ng-required="!form.phoneNo" type="text" name="emailid" ng-model="form.emailId" />
<div role="alert" ng-messages="userform.emailid.$error">
<div ng-message="required">
email id is required if phone no is not given.
</div>
</div>
</div>
</form>
Result:
Above approach can help us to achieve our goal.
Working example can be found here.
Cheers!
Happy Learning.