简体   繁体   中英

Angular custom validation not working for template-driven form

I am trying to create a custom validator that compares control to a specific number for template-driven form but for some reason, I can't get it to work. here's what I did so far

template:

<div class="td-c">
          <div class="form-group">
           <label class="quantity-label">
            <input  class="form-control" name="number"
               [(ngModel)]="product.item.quantity"
               [ngModelOptions]="{standalone: true}"
               (ngModelChange)="updateProductQuantity(i, product)"
               #quantity="ngModel"
               required
               quantityValidator>
           </label>
           <span *ngIf="quantity.hasError('quantityValidator')">error</span>
          </div>
         </div>

directive.ts file:

import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, FormControl, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
@Directive({
  selector: '[quantityValidator]',
  providers: [{
   provide: NG_VALIDATORS,
   useClass: QuantityValidatorDirective,
   multi: true
 }]
})
export class QuantityValidatorDirective implements Validator{
 
 @Input() quantity;
 
  constructor(){
   console.log('hello')
 }
  validate(c: FormControl) {
   return this.quantityValidator(5)(c)
 }
  quantityValidator(itemQuantity: number): ValidatorFn{
   return (control: FormControl): ValidationErrors | null => {
     if(control.value === itemQuantity){
       return null
    }else{
      return {
       isGreater: {valid: false}
     }
    }
     
  }
 }
}

any help will be greatly appreciated

It can be easily done by reactive forms. I am not sure why are you using the template-driven forms here. I don't think quantity.hasError('quantityValidator') would have a value. There won't be a hasError() method on quantity.

You can simply do it in the updateProductQuantity(i, product) . Declare a boolean variable as hasError in the ts file and check the quantity change in the updateProductQuantity() . If the validation fails change the value of hasError to true .

In template use like this,

 <span *ngIf="hasError">error</span>

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