Single-line JS implementation of the mobile Money format input rules

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.