Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional validations in angular2

I want to use same template for guest and customer registration forms but validations may varies as follows

Let us assume it is a Register form for Guests - firstName is required

<form #f="ngForm" novalidate (ngSubmit)="save()">
                <label>First Name:</label>
                <input type="text" name="firstName" [(ngModel)]="values.FirstName" required #firstName="ngModel">
                <div *ngIf="firstName.hasError('required') && (!firstName.pristine && !f.submitted)" class="text-danger">You must include a first name.</div>
</form>

And this is for Customer - firstName is optional

<form #f="ngForm" novalidate (ngSubmit)="save()">
                    <label>First Name:</label>
                    <input type="text" name="firstName" [(ngModel)]="values.FirstName" #firstName="ngModel">

</form>

I want to use same/onlyone template for both forms but validations varies! how could i achieve it. TIA!

NOTE: by using reactive forms I could achieve it, but knowingly I want to achieve in Template-Driven forms.

like image 812
k11k2 Avatar asked Jun 17 '26 15:06

k11k2


1 Answers

Based on this topic you can try

<input name="first" ngModel [required]="isRequired">
like image 126
A. Tim Avatar answered Jun 19 '26 07:06

A. Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!