'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
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rohithpoya |
