0

When using input type=number, there is a button to increment/decrement the value at the right of the input field. Can we restrict users from decrementing it to a negative value?

I know we can use min=0 in HTML input element but is there any other way to achieve this using Angular FormControl Validators?

(I can't use min=0 because the input element can be either number or text and this input is used in many places).

I'm trying to add Validators if the condition is match with the input. (e.g if (formInput.type === 'number') { formControl.addValidators(Validators.min(1)); }

I tried Validators.min(1) in FormControl but it still allows user to go past 0 when clicking the decrement button in input type=number field.

Thank you.

1
  • try adding a regex pattern Validators.pattern(your_regex) Commented Nov 9, 2022 at 4:30

1 Answer 1

0

Stackblitz example: https://angular-ivy-wckdgn.stackblitz.io

Subscribe to the control's valueChanges observable property. If the value is less than 0, set it to 0. Will look similar to the below.

Use {emitEvent: false} to prevent an infinite loop from setting the control's value in response to its value chaning

myControl.valueChanges.subscribe((val: number) => { if(val < 0) { myControl.setValue(0, {emitEvent: false}) } ) 
Sign up to request clarification or add additional context in comments.

2 Comments

It did restrict the user from going past 0 but after that I can't input anything on the input field since it will always set the value to 0 as soon as I type anything.
I've added a working example to my answer. If that doesn't help, please update your question with your updated code and we can look at it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.