0

I'm working on form based on material-design-lite plugin. Link below: https://getmdl.io/components/index.html#textfields-section

I have a problem with form validation, especially with regular expression.

There is my simple form:

<form action="#">
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="sample4">
    <label class="mdl-textfield__label" for="sample4">Number...</label>
    <span class="mdl-textfield__error">Input is not a number!</span>
  </div>
</form>

I would like to have such validation patterns:

  1. Input amount is not a string (only number 0-9)
  2. Separator must be ","
  3. I need max 2 decimal places
  4. I can't accept any characters, except of numbers 0-9 and ","
  5. Input amount cannot be less than 0
  6. Input amount has to start from a number

Could you please help me with these regular expressions? I don't have enough knowledge about it, just need ready patterns. Rest of validation I'm going to do via javascript.

Thank you!

1 Answer 1

1
^(?:[1-9][0-9]*?,?[0-9]{0,2}|[0](?:,[0-9]{0,2})?|)$

This seems to match all of the criteria you have provided, you can test it with this DEMO

It consists of 3 "parts" separated by |s essentialy testing for 3 different matches

  1. [1-9][0-9]*?,?[0-9]{0,2} - Matches if the input is a number starting from 1-9 followed by an amount (or lack) of numbers from 0-9 followed then by an optional ,+ 0-2 numbers from 0-9
  2. [0](?:,[0-9]{0,2})? - Matches if the input is 0 followed by an optional , and 0-2 numbers from 0-9
  3. (The lack of anything between the | and the )$ at the end) - Matches if the input is empty

EDIT: Here is a version which doesn't allow the last character to be a , https://regex101.com/r/dPM95O/4

Sign up to request clarification or add additional context in comments.

8 Comments

What about the max 2 decimal places?
Thank you, it's great solution! And what about such situation when comma is the last character? For example: "12,"?
@bigmeister : this doesn't solve your all conditions.
@NitinDhomse If you read the conditions it says, and I quote, "Input amount cannot be less than 0", which is technically saying it can be 0
@bigmeister : Decimal places means maximum digits accepted after decimal point (.), if you want amount max 2 digits then this is fine!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.