Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Simple input validation

I have a simple input that is meant for a phone number and I'd like to validate that there are only numbers and that the length is 10 digits long.

<input [(ngModel)]="client.phone" class="form-input" name="phone" type="phone" [value]="client.phone">

What can I do to validate this without using FormBuilder? It seems like FormBuilder just complicates things and I'd just like to validate this one input.

like image 431
Jeremy Thomas Avatar asked Apr 18 '17 19:04

Jeremy Thomas


People also ask

What is AbstractControl in Angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

What is ValidatorFn in Angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }

How do I use updateValueAndValidity?

You can subscribe to value changes of a control or the whole form. updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.


4 Answers

With the built in pattern validator it is very easy:

<input [(ngModel)]="client.phone" pattern="[0-9]{10}" class="form-input" name="phone" type="phone" [value]="client.phone">
like image 187
unitario Avatar answered Oct 16 '22 08:10

unitario


Here is an example from my Pluralsight course. This first example is using Template-driven forms. It is using a simple pattern to validate the email address:

            <div class="form-group"
                [ngClass]="{'has-error': (emailVar.touched || emailVar.dirty) && !emailVar.valid }">
                <label class="col-md-2 control-label" 
                    for="emailId">Email</label>

                <div class="col-md-8">
                    <input class="form-control" 
                           id="emailId" 
                           type="email" 
                           placeholder="Email (required)" 
                           required
                           pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+"
                           [(ngModel)]="customer.email"
                           name="email"
                           #emailVar="ngModel" />
                    <span class="help-block" *ngIf="(emailVar.touched || emailVar.dirty) && emailVar.errors">
                        <span *ngIf="emailVar.errors.required">
                            Please enter your email address.
                        </span>
                        <span *ngIf="emailVar.errors.pattern">
                            Please enter a valid email address.
                        </span>

                        <!-- This one does not work -->
                        <span *ngIf="emailVar.errors.email">
                            Please enter a valid email address.
                        </span>
                    </span>
                </div>
            </div>

This example uses Reactive Forms for the same thing.

    this.customerForm = this.fb.group({
        firstName: ['', [Validators.required, Validators.minLength(3)]],
        lastName: ['', [Validators.required, Validators.maxLength(50)]],
        email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
        sendCatalog: true
    });

So using a pattern is very much an Angular technique. I was just pointing you to the HTML site because it provided several suggestions for phone number patterns that you could pick from and use in place of the email patterns shown in my examples here.

Let me know if you want the link to the associated github code.

like image 45
DeborahK Avatar answered Oct 16 '22 10:10

DeborahK


<input type="number" name="phone" max="10">

you can use type number and max

like image 2
samnu pel Avatar answered Oct 16 '22 09:10

samnu pel


https://angular.io/docs/ts/latest/guide/forms.html

<form role="form" #f="ngForm" novalidate>
    <input class="form-input" type="number" [(ngModel)]="client.phone" name="phone" max="10">
    <button type="submit" [disabled]="f.form.invalid">
</form>
like image 1
Dmitrij Kuba Avatar answered Oct 16 '22 10:10

Dmitrij Kuba