Little refactored:
export function positiveNumberValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const isNotOk = Number(control.value) < 0;
return isNotOk ? { nonPositive: { value: control.value } } : null;
};
}
and if you want to use it in template as Directive
:
import { Directive, Input } from '@angular/core';
import { ValidatorFn, AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';
@Directive({
selector: '[prePositiveNumber]',
providers: [{ provide: NG_VALIDATORS, useExisting: PositiveNumberDirective, multi: true }]
})
export class PositiveNumberDirective implements Validator {
validate(c: AbstractControl): { [key: string]: any; } {
return positiveNumberValidator()(c);
}
}
export function positiveNumberValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const isNotOk = Number(control.value) < 0;
return isNotOk ? { nonPositive: { value: control.value } } : null;
};
}
Template:
<input type="number"
class="full"
name="shipmentVolume"
required
prePositiveNumber
[(ngModel)]="someModel" />
When using as Reactive forms
you can compose
validators, but also it can be used without compose
:
this.form = _formBuilder.group({
field:['', Validators.required, positiveNumberValidator()] });