Search code examples
javascriptregexvalidation

Text Input Real time JS validation as Float which accepts floating point and comma


I want to validate an input in real time way. The input has type text and must validate only an input having : number(s) and/or floating point or comma. Also the input accepts only two numbers after the floating point/comma. Examples :

  • 12.23    Valid
  • 12,23    Valid
  • 12.2      Valid
  • 12,02    Valid
  • 2           Valid
  • 12.035  Invalid
  • 12.36E Invalid
  • test       Invalid

EDIT :

Since I did not find the solution on stack and spent some hours to develop a solution that can help others i'll share what i've done :

I used the RegExp pattern to validate the number.but i can't do it with one pattern so i've created two patterns. The first validates: x*.yy And the second validates: x*,yy

Constraints : isNumeric doesn't accept float with comma.so that's why i've converted it.

The function validation function code :

function validateCurrencyPattern(price){
    var patt = new RegExp(/[0-9]+[.]{1}[0-9]{2}/i);
    var convertedPrice =price.replace(',', '.');
    var matchedString = price.match(patt)  ;
    var matchedString2 = convertedPrice.match(patt)  ;
    if (matchedString) {
        return matchedString
    }
    if (matchedString2) {
        return matchedString2
    }
    if((!$.isNumeric(convertedPrice))|| convertedPrice<0){
        return null;
    }
    else if(!matchedString && !matchedString2){
      return  convertedPrice;

    }
}
$(document).on("keypress keyup blur","#field", function (event) {
 $(this).val(validateCurrencyPattern($(this).val()));
});

and The call for function mixing the events (keypress keyup blur)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
 <input type="text" id="field" name="field" pattern="^\d+(?:\.\d{1,2})?$"/>
 <input type="Submit"/>
</form>

Solution

  • I suggest tracking the live input validation with a /^(\d*)([,.]\d{0,2})?$/ regex that allows typing any 0 or more digits at the start, and then an optional substring of , or . and then 0, 1 or 2 digits. If there is a match, re-format the value by replacing , with .. If there input value is not matched, replace it with the last good value (say, introduce a variable called prevValue for that).

    Once you want to submit this value, you need to make sure the value is in the final format, that is, there should be no . at the end. To enable this, add a pattern attribute to your <input> and assign the ^\d+(?:\.\d{1,2})?$ regex to it. Here, it will already require 1+ digits at the start of the string, and then will match an optional substring of a . followed with 1 or 2 digits. See the regex demo. Since the comma will get replaced with a dot, you need no [.,] pattern, \. is enough.

    Also, it is a good idea to handle the input value change on paste.

    var prevValue = "";
    var patt = /^(\d*)([,.]\d{0,2})?$/;
    
    function validateCurrencyPattern(price){
        var matchedString = price.match(patt);
        if (matchedString) {
            prevValue = matchedString[1] + (matchedString[2] ? matchedString[2].replace(",", ".") : "")
            return prevValue;
        }
        else {
          return prevValue;
       }
    }
    $(document).on("keypress keyup blur paste","#field", function (event) {
     $(this).val(validateCurrencyPattern($(this).val()));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
     <input type="text" id="field" name="field" pattern="^\d+(?:\.\d{1,2})?$"/>
     <input type="Submit"/>
    </form>