Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Form Validation on blur

Tags:

angular6

I want to validate input filled in onBlur how can i do this. please help me.

<form class="form-horizontal" role="form" name="form" id="form"
                (ngSubmit)="f.form.valid && onSubmit()"
                #f="ngForm" novalidate>

    <input type="text" class="form-control" placeholder="Social Id"
        [ngModel]="generalUserData.socialId" [maxlength]=12 name="socialId" [minlength]=10
        (blur)="onBlurMethod($event.target.name, $event.target.value ,generalUserData)"
        #socialId="ngModel" [ngClass]="{ 'is-invalid': f.submitted && socialId.invalid }"
        pattern="\d{9}(v|V)|\d{12}" required/>
    <div *ngIf="f.submitted && socialId.invalid" class="invalid-feedback">
        <div *ngIf="socialId?.errors.required">NIC is required</div>
        <div *ngIf="socialId?.errors.minlength">NIC must be at least 10 characters long.</div>
        <div *ngIf="socialId?.errors.pattern">Not valid NIC</div>
        <div *ngIf="socialId?.errors.maxlength">NIC must be less than 12 characters long.</div>
    </div>
</form>

I used below sample link and then I want to validate as on blur how can I do this.

like image 534
Thilina Sampath Avatar asked Mar 02 '26 08:03

Thilina Sampath


1 Answers

The onBlur() method has been changed since Angular 5. With template-driven forms you need to use the following syntax:

<input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">

Here is the demo, hope it can help you :

https://codingthesmartway.com/angular5-forms-update/

like image 167
chloe Avatar answered Mar 04 '26 18:03

chloe



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!