【问题标题】:Angular validate rule for unique text value唯一文本值的角度验证规则
【发布时间】:2021-08-29 16:47:05
【问题描述】:

我有这样的角度表:

<tbody>
    <tr *ngFor="let book of books" [ngClass]="{'isActiveBooks' : !book.isActive}">

        <td>
            <div class="text-description" [appLongText]="book.bookName" ngbTooltip="{{book.bookName}}" [maxTextLength]="45"></div>
        </td>
        <td>
            <input type="number" min="1" class="book-order-input"
                placeholder="Enter" (change)="orderChanged=true"
                [(ngModel)]="book.bookOrder"
                >
        </td>       
    </tr>
</tbody>

我想在 bookOrder 控件中添加 unqiue 验证。因此,如果两本书有 2 个相同的值,则会显示错误。

【问题讨论】:

    标签: angular validation


    【解决方案1】:

    如果您拥有books 的完整列表,并且您想在客户端进行此验证,您可以定义一个新的验证器指令,如下所示:

    @Directive({
        selector:
            '[checkUniqueWithin][ngModel],[checkUniqueWithin][formControl],[checkUniqueWithin][formControlName]',
        providers: [{ provide: NG_VALIDATORS, useExisting: CheckUniqueValidatorDirective, multi: true }],
    })
    export class CheckUniqueValidatorDirective implements Validator, OnChanges {
        private _validator: ValidatorFn = this._nullValidator;
        private _onChange?: () => void;
    
        @Input()
        checkUniqueWithin!: Book[];
    
        ngOnChanges(changes: SimpleChanges): void {
            if (changes.checkUniqueWithin) {
                this._createValidator();
                if (this._onChange) this._onChange();
            }
        }
    
        validate(control: FormControl): ValidationErrors | null {
            return this._enabled() ? this._validator(control) : null;
        }
    
        registerOnValidatorChange(fn: () => void): void {
            this._onChange = fn;
        }
    
        private _enabled(): boolean {
            return !!this.checkUniqueWithin;
        }
    
        private _createValidator(): void {
            this._validator = this._enabled()
                ? this._uniqueValidator(this.checkUniqueWithin)
                : this._nullValidator;
        }
    
        private _uniqueValidator(source: Book[]): ValidatorFn {
            return (control: AbstractControl): ValidationErrors | null => {
                if (source.filter((book) => book.bookOrder === control.value).length > 1) {
                    // Return error (i.e. invalid) if there is another book with the same value:
                    return { unique: true };
                }
                // Return null (i.e. valid) if there is no book with the same value:
                return null;
            };
        }
    
        private _nullValidator(control: AbstractControl): ValidationErrors | null {
            return null;
        }
    }
    
    

    然后您可以在模板中使用它,如下所示:

        <input
            type="number"
            min="1"
            class="book-order-input"
            placeholder="Enter"
            (change)="orderChanged = true"
            [(ngModel)]="book.bookOrder"
            [checkUniqueWithin]="books"
        />
    

    但是如果你没有所有的书,那么你需要创建 AsyncValidator 而不是普通的,在服务器端检查唯一性,并将结果返回为Observable

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2015-07-09
      • 2015-04-04
      • 2016-04-08
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多