简体   繁体   中英

Javascript currency regular expression replace

For my business web application I want a user to only be able to enter valid currency values in a textbox.

Currently I use

$input.val($input.val().replace(/[^.\d]/g, ''));

But this doesn't take in consideration order or multiple decimal seperators.

So the user either has to enter a whole integer or a valid decimal value eg:

  • 49
  • 49.50

Bonus points if this is allowed too:

  • .50 (for 0.50)

So I don't want to validate, I want to restrict typing into the textbox. Is this possible with a single regexp replace?

We can do this in two steps. Restrict the user to type only the number characters and . character.

var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode < 31 && (charCode > 48 || charCode < 57))
    return true;
return false;

And the next one is for allowing the . :

var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
    return true;
return false;

The next step will be not allowing double periods.

var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
    if (charCode == 46 && value.indexOf(".") !== false)
        return true;
return false;

Hope you can have this as a starting point.

Snippet

Open Deal: Break it if you can.

 function check(inp) { var charCode = (event.which) ? event.which : event.keyCode; console.log(charCode); if (charCode == 8) return true; if ((charCode > 46 && charCode < 58) || (charCode > 95 && charCode < 106) || charCode == 110 || charCode == 190) if (charCode == 110 || charCode == 190) if (inp.value.indexOf(".") == -1) return true; else return false; else return true; return false; } 
 <input type="text" onkeydown="return check(this);" /> 

It's more user friendly to advise of errors and let users fix them themselves. You might consider using the keyup event, but showing an error too early (before the user has had a chance to enter a valid value) can be annoying too. eg

 function validate(el) { var type = el.className; var errEl = document.getElementById(el.name + 'Err'); if (type == 'typeCurrency') { var currencyRe = /^-?(\\d+(\\.\\d{1,2})?|\\.\\d{1,2})$/; errEl.style.visibility = currencyRe.test(el.value)? 'hidden' : 'visible'; } } 
  .errorMessage { color: red; background-color: white; visibility: hidden; } 
 Cost&nbsp;<input onblur="validate(this)" name="foo" class="typeCurrency" placeholder="0.00"><br> <span id="fooErr" class="errorMessage">Please enter a valid cost, eg 2.45</span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM