Angular 6-模糊形式验证

时间:2018-08-06 09:37:19

标签: angular6

我想验证在onBlur中填写的输入,我该怎么做。请帮助我。

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

我在下面的示例link中使用过,然后我想在模糊时进行验证。

2 个答案:

答案 0 :(得分:1)

自Angular 5起,onBlur()方法已更改。使用模板驱动的表单,您需要使用以下语法:

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

这是演示,希望它可以为您提供帮助:

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

答案 1 :(得分:0)

我这样更新下面的代码

<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 || socialIdType.touched) && socialId.invalid }"
    pattern="\d{9}(v|V)|\d{12}" required/>
<div *ngIf="(f.submitted || socialIdType.touched) && 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>

现在一切正常。