Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Reactive form Validator - how to allow null, but when there is input, the input need to be number?

I have this forming group like so:

   channelInfo: this.fb.group({
    youTubeSubs: [null, [Validators.required, CustomValidators.number]],
    instagramFollowers: [null],
    twitterFollowers: [null],
    snapchatFollowers: [null],
    facebookLikes: [null]
  }),

Only the youTubeSubs is required, all the other number is optional. But if there is value, I need to make sure the value to be number using the CustomValidators.number provide by this component: Angular2 Validator

How can I allow null and number validator at the same time? So if value is empty null, it will show error. But if there is value, the error will show if the value is not number?

like image 987
Hugh Hou Avatar asked Dec 30 '25 14:12

Hugh Hou


1 Answers

Just remove the Validators.required when validating the other fields like so..

channelInfo: this.fb.group({
    youTubeSubs: [null, [Validators.required, CustomValidators.number]],
    instagramFollowers: [null, [CustomValidators.number]],
    twitterFollowers: [null, [CustomValidators.number]],
    snapchatFollowers: [null, [CustomValidators.number]],
    facebookLikes: [null, [CustomValidators.number]]
}),
like image 171
cozmik05 Avatar answered Jan 01 '26 11:01

cozmik05



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!