简体   繁体   中英

Angular string and number validation error

<mat-form-field>
    <input matInput placeholder="Protokol Detayı" type="text" required="true" name="detail" id="detail"
                                    #detail="ngModel" ngModel required>
</mat-form-field>
<mat-error *ngIf="detail.touched && detail.invalid">
    <div *ngIf="detail.errors.required">Bu alanı boş geçemezsiniz.</div>
</mat-error>

I want to show an error if the input gets number instead of letters. But I could not manage to do it. I think I am right in writing the type of the input.

There are two ways you could achieve this. 1] Do not allow numbers to be entered in the input box. Display no errors 2] use pattern attribute on input and display errors when the entered text does not match the input for example the following pattern will take only alphabets and will give error when the user enters numbers.

<mat-form-field>
        <input matInput placeholder="Protokol Detayı" type="text" required="true" name="detail" id="detail"
                                    #detail="ngModel" [pattern]="[a-zA-Z]+$" ngModel required>
    </mat-form-field>
    <mat-error *ngIf="detail.touched && detail.invalid">
        <div *ngIf="detail.errors.required">Bu alanı boş geçemezsiniz.</div>
        <div *ngIf="detail.errors.pattern">numbers not allowed.</div>

    </mat-error>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM