Reputation: 193
<input type="text" id="price" />
$('#price').keyup(function(){
$('#price').val($('#price').val().replace(',', '.'));
})
Demo: http://jsfiddle.net/2KRHh/1/
This replaces ,
with .
. This is OK, but I would like to replace all characters which are not numbers with NULL. How can I do this with a regular expression?
Upvotes: 0
Views: 2403
Reputation: 51191
From the point of usability, it makes not much sense to guess what the user might have wanted or not and then try to correct those errors. Just use a pattern like following:
<input class="" type="text" id="price" pattern="\d+\.\d\d"/>
Modern browsers will validate the input field according to the pattern, and you can use $(this).attr("pattern")
to also validate against it.
Now if it does not match, just prompt the user to kindly correct their input.
In it's simplest form it might look like the following example. It just does a simple replace on the input (,->.) (this might not even be necessary if you use the pattern "\d+[.,]\d\d"
and correct it afterwards to your liking) and then tries to validate. If it fails, the user cannot commit and is prompted to correct their input.
Upvotes: 3
Reputation:
You may want to take a look at my jQuery iMask plugin, though what you're asking for specifically:
.replace( /.*?(\d+)(?:\.(\d{1,2}))?.*/, function( rx, dollars, cents ){
cents = +( cents || 0 );
return (+dollars + (cents/((cents<10)?10:100))).toFixed(2);
} );
If you just want to strip non-numeric numbers:
.replace( /[^0-9.]/g, '' )
Upvotes: 2