3

我在用户信息表单中使用了验证,如下所示。

this.userInfoForm = this.fb.group({
    retrieveId: [''],
    customerName: [[],[UtilityService.checkMinLength(3, 50)]],
});

我创建了以下服务来检查验证

 @Injectable()
 export class UtilityService {
     static checkMinLength(min: number, max: number): ValidatorFn {
         return (c: AbstractControl) => {
             if (c.value && c.value != undefined) {
                 return {
                     'checkMinLength': c.value.some((a) => {
                         if (a.itemName.length < min || a.itemName.length > max) { return true; }
                         return null;
                      })
                 };
            }
        }
    }

在 HTML 中使用 checkMinLength 检查customername字段的验证。这些验证工作正常,但是当我检查表单状态时,它显示“无效”。对于 ng-select 控件,提交按钮始终处于禁用状态

<form class="form-horizontal" novalidate (ngSubmit)="saveInfo()" [formGroup]="userInfoForm" autocomplete="off">
    <fieldset>
        <div class="form-group padding-top-bottom" [ngClass]="{'has-error': (userInfoForm.get('customerName').touched || userInfoForm.get('customerName').dirty) &&!userInfoForm.get('customerName').valid }">
            <label class="col-md-4" for="customerNameId" tooltip={{attributeNames.customerNameTitle}} data-placement="right">Customer Name</label>
            <div class="col-md-7">
                <ng-select [items]="customerName" multiple="true" [addTag]="true" bindLabel="itemName" (change)="onItemSelect($event,'customer','customerName')" formControlName="customerName" [(ngModel)]="customerName"></ng-select>
                <span class="help-block" *ngIf="userInfoForm.get('customerName').touched ||userInfoForm.get('customerName').dirty) &&userInfoForm.get('customerName').errors">
                    <span *ngIf="userInfoForm.get('customerName').errors.checkMinLength">End Customer Name must be longer than 3 characters.</span>
                </span>
           </div>
       </div>
       <button class="btn btn-primary" id="submitForm" type="submit" [disabled]="!userInfoForm.valid || !userInfoForm.dirty">Save</button>
    </fieldset>
</form>
4

1 回答 1

3

如果控件有效,您的验证器必须返回“null”(不是具有属性 null 的对象)

export class UtilityService {
 static checkMinLength(min: number, max: number): ValidatorFn {
     return (c: AbstractControl) => {
         if (c.value && c.value != undefined) {
             return {
                 'checkMinLength': c.value.some((a) => {
                     if (a.itemName.length < min || a.itemName.length > max) { return true; }
                  })
             };
        }
        return null; // LOOK HERE
    }
}
于 2018-07-02T23:33:02.733 回答