Reputation: 8089
Suppose we're building an address book application (contrived example) with AngularJS.
We have a form for contacts that has inputs for email and phone number, and we want to require one or the other, but not both: We only want the email
input to be required if the phone
input is empty or invalid, and vice versa.
Angular has a required
directive, but it's not clear from the documentation how to use it in this case. So how can we conditionally require a form field? Write a custom directive?
Upvotes: 238
Views: 175646
Reputation: 3
For Angular 2
<input [(ngModel)]='email' [required]='!phone' />
<input [(ngModel)]='phone' [required]='!email' />
Upvotes: 0
Reputation: 3242
In AngularJS (version 1.x), there is a build-in directive ngRequired
<input type='email'
name='email'
ng-model='user.email'
placeholder='[email protected]'
ng-required='!user.phone' />
<input type='text'
ng-model='user.phone'
placeholder='(xxx) xxx-xxxx'
ng-required='!user.email' />
In Angular2 or above
<input type='email'
name='email'
[(ngModel)]='user.email'
placeholder='[email protected]'
[required]='!user.phone' />
<input type='text'
[(ngModel)]='user.phone'
placeholder='(xxx) xxx-xxxx'
[required]='!user.email' />
Upvotes: 0
Reputation: 17115
For Angular2
<input type='email'
[(ngModel)]='contact.email'
[required]='!contact.phone' >
Upvotes: 15
Reputation: 188
Simple you can use angular validation like :
<input type='text'
name='name'
ng-model='person.name'
ng-required='!person.lastname'/>
<input type='text'
name='lastname'
ng-model='person.lastname'
ng-required='!person.name' />
You can now fill the value in only one text field. Either you can fill name or lastname. In this way you can use conditional required fill in AngularJs.
Upvotes: 14
Reputation: 771
if you want put a input required if other is written:
<input type='text'
name='name'
ng-model='person.name'/>
<input type='text'
ng-model='person.lastname'
ng-required='person.name' />
Regards.
Upvotes: 26
Reputation: 8089
There's no need to write a custom directive. Angular's documentation is good but not complete. In fact, there is a directive called ngRequired
, that takes an Angular expression.
<input type='email'
name='email'
ng-model='contact.email'
placeholder='[email protected]'
ng-required='!contact.phone' />
<input type='text'
ng-model='contact.phone'
placeholder='(xxx) xxx-xxxx'
ng-required='!contact.email' />
Here's a more complete example: http://jsfiddle.net/uptnx/1/
Upvotes: 473