Oliveira
Oliveira

Reputation: 1341

JavaScript Regular Expression for Money non JQuery

I need a money mask for an input, the problem is that I can't use jquery on my application.

How can I do this using regular expression 'on key up' for example?

here is my code:

<tr>
    <td>
        money:
            <input type="text" class="money"  maxlength="22" id="money" name="money">
        </td>
    </tr>

I the format to look like like 00.000,00

Upvotes: 2

Views: 1903

Answers (2)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

Try something like this

There is a problem with trying to validate text as it's being typed which can be illustrated with this http://jsfiddle.net/denomales/dgeH2/. As the text field is updated if the current string matches or not will be displayed directly below.

  • ^[0-9]{1,3}(?:\.[0-9]{3})*(?:\,[0-9]{2})?$ will match currency in the format 00.000,00 as requested in the comments

enter image description here

  • ^[0-9]{1,3}(?:\,[0-9]{3})*(?:\.[0-9]{2})?$ will match currency in the format 00,000.00

enter image description here

Upvotes: 0

PhilTrep
PhilTrep

Reputation: 1641

It is impossible to give you a direct answer since you didn't provide the format...

The JavaScript way of testing a regex on a string is:

function regexmoney(){
    var patt=new RegExp(pattern,modifiers);
    var string = document.getElementById('money').value;
    var result = patt.test(string);//Returns true/false
    if(!result){
         var charArray=string.split();
         //Iterate through the array and arrange the chars as 
         //you see fit (returning moneyresult)
         document.getElementById('money').value = moneyresult;
    }
}

Then the HTML:

<tr>
<td>
    money:
        <input type="text" onkeyup="regexmoney()" class="money"  maxlength="22" id="money" name="money">
    </td>
</tr>

And to generate the regex http://txt2re.com/

Hope this helps...

Upvotes: 1

Related Questions