Single-line JS implements the input rules of the mobile terminal's money format, js money

Source: Internet
Author: User

Single-line JS implements the input rules of the mobile terminal's money format, js money

Money format testing is a common requirement. I remember that when I first encountered this requirement at work, I did not quite write regular expressions and found a similar solution, the regular expression document is changed to the desired form.

However, the user's input operations are arbitrary, but the prompt information is displayed. Although this method can meet the requirements, it is unfriendly.

In fact, many mobile applications block incorrect input when entering money. They can only enter the correct format. First, let's take a look at the input rules of the money format:

1. Do not enter blank characters or letters
2. Only numbers and decimal places can be entered.
3. the first digit cannot be a decimal point
4. the decimal point can only appear once
5. There are only two digits after the decimal point
6. You cannot enter multiple digits with the first digit being 0.

A seemingly simple question can be considered very well. However, the code can be easily written, and I have spent a lot of time exploring it. Only one row is required for validation.

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 ');}

It's not too early. Let's write so much, and finally paste the Demo I wrote in CodePen, hoping to help people who need it.

The above section describes how to use single-line JS to implement the input rules for mobile terminal money formats. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.