onTheInternet
onTheInternet

Reputation: 7253

How to format user input to allow xx.xx format

I have an input field that I want to format so it only allows currency but in a xx.xx or just xx format.

I do not want to allow

So these examples would be acceptable

1 | 1.12 | 22.22 | 123 | 1234.44 | .55 

But these would not be

$1, | 1.11.11 | .11.11 | , | 1,000

I've written this regex statement that I think does this

\d{0,}(\.\d{1,2})? 

And I've written the javascript that I thought would give me the formatted value. But it throws an error

   $('#Overlay').on('keyup', '#Amount', function(event) {
       var val = $('#Amount').val();

        var replaceVal = this.value.replace(\d{0,}(\.\d{1,2}), '');
        if(this.value != replaceVal){
          this.value = replaceVal;
        }

   });  

Uncaught SyntaxError: Invalid or unexpected token.

Just so it's clear, if a user types in an invalid character the code should fire and remove the problem. So if a user types 12.12. it should append 12.12 to the input field.

Upvotes: 0

Views: 674

Answers (1)

Your unexpected token is in

replace(\d{0,}(\.\d{1,2}), "")

regex starts with

/\d{0,}(\.\d{1,2})/g

you may want to try string.match(regexp) for your problem. JavaScript String match() Method If your text does not match just cut the last char of the string

Upvotes: 1

Related Questions