Hello I'm building a form in Angular with FormBuilder and i want to put a validation in Validators.pattern() that prevents values less than or equal to zero and that accepts decimal values
How would the regex expression look? Thanks.
Hello I'm building a form in Angular with FormBuilder and i want to put a validation in Validators.pattern() that prevents values less than or equal to zero and that accepts decimal values
How would the regex expression look? Thanks.
Copyright © 2021 Jogjafile Inc.
Don't. Sure, you could use something like
^([1-9]\d*(\.\d+)?|0\.\d+)$, but you're better off restricting the input in other ways, like<input type="number" id="quantity" name="quantity" min="0">for example.Explanation of the regex
First of all, it's anchored between
^and$, so the entire input must be matched. Then, there are two options, separated by|:[1-9]a digit between 1 and 9\d*followed by any number of digits(\.\d+)?optionally followed by a decimal point and at least one digit0a zero\.\d+followed by a decimal point and at least one digitNote that if it starts with a zero, the decimal point and a following digit are mandatory, while if there's any other leading digit, the decimal point and following digits are optional, although if there is a decimal point, there should be at least one digit after that.