'Regex which validate specific positive number values only
I want to validate numbers in an input in Javascript.
The input should accept:
empty input ''
positive number '123'
decimal number '23.89' '23.88888' '.89'
But it shouldn't accept negative numbers and also '0.-99' I have used this regex:
pattern="/[+]?[0-9]+\.?[^-]?[0-9]*/";
But it accepts 0.-99 . What is the correct regex to not accept .-99
Solution 1:[1]
Try this:
/^([.\d][\d]*\.?[\d]+)/g
/
^ beginning of the input
(
[.\d] starting charater of the input should be either a '.', or a digit
[\d]+ then any number of digits after the first character
\.? matches the decimal '.', ? indicates that it is optional
[\d]+ matches digits after the decimal position
)
/
g js re global flag
Test this regex here: https://regex101.com/r/c5ELUl/1
Solution 2:[2]
The next provided example code features both, a final validation and an immediate input value sanitizing. Both tasks are regex based.
The former covers the OP's acceptance criteria ... the pattern is as follows ... /^(?<=-*)\+?\d*\.?\d+$|^(?<=-*)\+?\d+\.$/.
The latter restricts user input while typing continues or copy-paste happens ... the pattern is based on the above, more strict, pure validation ... /^(?<=-*)(?<sign>\+?)(?<integer>\d*)(?<point>\.?)(?<float>\d*)/.
function isValidNumberValue(value) {
value = String(value);
return (
(value === '') ||
(/^(?<=-*)\+?\d*\.?\d+$|^(?<=-*)\+?\d+\.$/).test(value)
// see ... [https://regex101.com/r/ddMyLD/4]
//(/^(?<=-*)\+?\d*\.?\d+$/).test(value)
// // see ... [https://regex101.com/r/ddMyLD/2]
);
}
function validateNumberValue({ currentTarget }) {
currentTarget.classList.toggle('invalid', !isValidNumberValue(currentTarget.value));
}
function resetValidation({ currentTarget }) {
currentTarget.classList.remove('invalid');
}
function sanitizeImmediately({ currentTarget }) {
let { value } = currentTarget;
value = value.trim();
const {
sign = '', integer = '', point = '', float = ''
} = (/^(?<=-*)(?<sign>\+?)(?<integer>\d*)(?<point>\.?)(?<float>\d*)/)
// see ... [https://regex101.com/r/ddMyLD/1]
.exec(
currentTarget.value.trim()
)
?.groups ?? {};
currentTarget.value = [sign, integer, point, float].join('');
}
function init() {
const control = document.querySelector('[type="text"]');
control.addEventListener('input', sanitizeImmediately);
control.addEventListener('focusin', resetValidation);
control.addEventListener('focusout', validateNumberValue);
}
init();
console.log(
"isValidNumberValue('') ?..",
isValidNumberValue('')
);
console.log(
"isValidNumberValue(' ') ?..",
isValidNumberValue(' ')
);
console.log(
"isValidNumberValue('-0') ?..",
isValidNumberValue('-0')
);
console.log(
"isValidNumberValue('0') ?..",
isValidNumberValue('0')
);
console.log(
"isValidNumberValue(.45) ?..",
isValidNumberValue(.45)
);
console.log(
"isValidNumberValue(-.45) ?..",
isValidNumberValue(-.45)
);
console.log(
"isValidNumberValue('.-45') ?..",
isValidNumberValue('.-45')
);
console.log(
"isValidNumberValue(99.432) ?..",
isValidNumberValue(99.432)
);
console.log(
"isValidNumberValue('+9.43') ?..",
isValidNumberValue('+9.43')
);
console.log(
"isValidNumberValue('+9.43.45') ?..",
isValidNumberValue('+9.43.45')
);
console.log(
"isValidNumberValue('5.') ?..",
isValidNumberValue('5.')
);
console.log(
"isValidNumberValue('.') ?..",
isValidNumberValue('.')
);
body { margin: 0; }
[type="text"].invalid { border-color: #b00; background-color: #fddddd; }
.as-console-wrapper { min-height: 88%!important; }
<input type="text" maxlength="16" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anotherGatsby |
| Solution 2 |
