Reputation: 198
inputField: new FormControl('', [Validators.required])
when the user enters '0' in the field, the error required is applied on the control.
Zero should be considered as a value.
Upvotes: 4
Views: 10165
Reputation: 6235
You could create method, that matches whatever regex you input and then validates based on that. For example, lets not allow zero.
control: new FormControl('', [Validators.required, this.notAllowed(/^0/)])
/**
* Regex form validator
*/
notAllowed(input: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = input.test(control.value);
return forbidden ? {notAllowed: {value: control.value}} : null;
};
}
Upvotes: 2
Reputation: 86790
By default, If you enter anything into formControl element angular form will treat it as truthy value -
inputField: new FormControl(0, [Validators.required]) //valid
inputField: new FormControl('', [Validators.required]) //invalid
But yes, you can add some regex pattern as well to check value match for 0
only, for example -
inputField = new FormControl(0, [Validators.required, Validators.pattern(/^[1-9]*$/)])
Upvotes: 7
Reputation: 29335
you're mistaken somewhere.
stackblitz shows 0 meets a required validator: https://stackblitz.com/edit/angular-bmqvtq?file=src/app/app.component.ts
Upvotes: 4