My goal is to develop a javascript regular expression that specifically identifies valid Javascript-style numbers. The requirements entail accommodating an optional minus or plus sign before the number, recognizing the decimal dot, and supporting exponent notations such as 1e-4 or 1E4, with an additional option for a sign in front of the exponent if necessary.
The pattern should allow digits before or after the dot, but it should not match just a standalone dot. Examples like .2 and 2. should be considered valid, whereas only the dot should not be accepted.
The ideal scenario is to encapsulate the expression within /^...$/; format.
I've managed to cover some aspects, but I aim for my expression to successfully validate common javascript values like .5, -.5, or +5
function validNumber(number) {
var regexNum = /^-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?$/;
return regexNum.test(number);
}
console.log(validNumber("0.0001")); // true
console.log(validNumber("-5")); // true
console.log(validNumber("0.3425")); // true
console.log(validNumber("1e-4")); // true
console.log(validNumber("1E-4")); // true
console.log(validNumber("1Ee-4")); // false
console.log(validNumber("-4.34")); // true
console.log(validNumber("Test123")); // false
console.log(validNumber("+-2")); // false
console.log(validNumber("5.")); // true
console.log(validNumber(".")); // false
console.log(validNumber(".5")); // Should be true, but passes as false
console.log(validNumber("-.5")); // Should be true, but passes as false
console.log(validNumber("+5")); // Should be true, but passes as false
Do you have any recommendations for this?