Angular 2: simple input validation

I have a simple input that is for a phone number, and I would like to confirm that there are only numbers and a length of 10 digits.

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

What can I do to verify this without using FormBuilder? It seems like it FormBuilderjust complicates the situation, and I just wanted to confirm this entry.

+4
source share
4 answers

Using the built-in validation template is very easy:

<input [(ngModel)]="client.phone" pattern="[0-9]{10}" class="form-input" name="phone" type="phone" [value]="client.phone">
+3
source

<input type="number" name="phone" max="10">
Run codeHide result

you can use type number and max

+2
source

Pluralsight. . :

            <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.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
    });

, - Angular. HTML, , , .

, github.

+1

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>
+1

Source: https://habr.com/ru/post/1675081/


All Articles