Money format test is very common needs, remember the first time in the work encountered this demand, not very will write regular expression, found a similar solution, looking at the regular document changed to the form of their own needs.
But the user's input action is arbitrary, just display the prompt information, this way although can satisfy the request, but feel unfriendly.
In fact, many applications on the mobile side of the input money is masked error input, can only enter the correct format. Let's take a look at the input rules for money formats:
1. Cannot enter blank characters and letters
2. Only numbers and decimal points can be entered
3. The first cannot be a decimal point
4. The decimal point can only occur once
5. Only two digits after the decimal point
6. The number of digits that cannot be entered first is 0
Seemingly very simple problem, in fact, should be considered very thoughtful. But the code can be written very concise, I spent a lot of effort to grope out. Only one row is really needed for the validation section
function Moneyformat (str) { return str.replace (/[^\d\.]| ^\./g, '). Replace (/\.{ 2}/g, '. '). Replace (/^ ([1-9]\d*|0) (\.\d{1,2}) (\.| \d{1})? $/, ' $1$2 '). Replace (/^0\d{1}/g, ' 0 ');}
Time is not early, write so many, finally affixed to my codepen written in the Demo, hoping to help people in need.
See the Pen Moneyformat by Zongbin (@nzbin) on Codepen.
Single-line JS implementation of the mobile Money format input rules