Trying to write a javascript regex for forcing users to enter decimal after a whole number, doesn't seem like many people want to do this as my searches have yielded nothing that suits my needs.
Match: 2.00 20.00 200.00 1.73 0.10
No Match: .2 .20 . 1 10 1.0 0.1 1.
Here is what I have currently:
var regexp=/^[0-9]{1,}\\.{1}[0-9]{2}$/;
In plain english, users must enter money in X.XX format. Just a whole number by itself is disallowed.
I'd appreciate any help and also teaching insight anyone has to offer in making this work.
EDIT:
Here is code:
var notempty=/[a-zA-Z0-9\.\$]/g;
var money=/^[0-9]{1,}\.{1}[0-9]{2}$/;
if ( (notempty.test(document.getElementById('numbers').value)) && (!money.test(document.getElementById('numbers').value)) )
{alert('Wrong format');}
Your initial regular expression is correct, the problem is actually your notempty
check can short-circuit the condition if the value is false
. For example if you have a character which is not a letter, number, dollar sign, or period the /[a-zA-Z0-9\\.\\$]/
it will evaluate false
and ignore the item after the &&
as the values don't matter because false && [any conditions] = false
. For example if the input value was "+"
:
if ( false && ... )
// invalid format [the expression was false, so this isn't ran]
Since the first condition is false
the entire expression becomes false, leading to a improper "correct format"
. The "empty check" isn't needed in this case anyway, you can simply have:
if (money.test(document.getElementById('numbers').value) {
// valid format
} else {
// invalid format
}
As noted by @JostCrozier, your expression can be simplified to: /^\\d+\\.\\d{2}$/
, which is functionally equivalent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.