javascript – How to make a regex for a number with 6 digits (integer or decimal, negative or positive) or fraction, no comma and no float (JS)
/^-?\d{1,5}(\/\d{1,5})?(\/\d{1,5})?$|^\d{1,5}(\/\d{1,5})?(\/\d{1,5})?$/
- ^ and $ are the start and end of the string anchors, which ensure
that the entire string matches the pattern. - -? matches an optional minus sign, allowing for positive or negative numbers.
- \d{1,5} matches one to five digits.
- (/\d{1,5})? matches an
optional fraction part, which consists of a forward slash / and one
to five digits. This is repeated twice to allow for a maximum of
three fraction parts. - | separates two alternative patterns. The first
pattern matches negative numbers with one to three fraction parts,
and the second pattern matches positive numbers with one to three
fraction parts.
This regular expression does not validate the requirement that the decimal point must be represented by a period . and not a comma ,. To enforce this restriction, you can add an additional check in your code to replace all commas with periods before checking the input against this regular expression like so:
const regex = /^-?\d{1,5}(\/\d{1,5})?(\/\d{1,5})?$|^\d{1,5}(\/\d{1,5})?(\/\d{1,5})?$/;
function validateInput(input) {
input = input.replace(/,/g, '.');
return regex.test(input);
}
const input = "-1,234/567/890";
console.log(validateInput(input)); // Output: true
This function takes the input as a parameter, replaces all commas with periods using the replace method, and then tests the modified input against the regular expression using the test method.
Read more here: Source link
