Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - JavaScript regex allow only numeric and minus sign as first character

I want users to enter numeric values only in my input hence I put below code.

<input type="text" class="form-control rounded-pill bg-light" autocomplete="off" name="free_credit_amount" id="free_credit_amount" placeholder="Free credit amount">

$('body').on('keyup', '#free_credit_amount', function(){
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This is working fine for me .. however I have a requirement that, users can enter negative values as well .. something like -500 , hence I have updated my JavaScript Regex a bit with something like following ..

$('body').on('keyup', '#free_credit_amount', function(){   
   this.value = this.value.replace(/[^-0-9]/g,'');
});

This is also working fine for me as I am able to type minus (-) sign and can enter a value something like 500 or -500 however, I want to furnish this regex a bit .. Currently what is happening, I can also enter a value like 500-. This should not be allowed .. I only want my minus (-) to be only added as first character..

I have tried to use various other REGEX like this.value = this.value.replace(/(\+|\-)?[^-0-9]/g,''); this.value = this.value.replace(/^[-][a-zA-Z0-9.,$;]/g,'');

But none of those REGEX working for me ..

Can someone help me to achieve this plz ..

Thanks

like image 598
Mittul At TechnoBrave Avatar asked Sep 12 '25 04:09

Mittul At TechnoBrave


1 Answers

You can use

$('body').on('input', '#free_credit_amount', function(){
    var position = this.selectionStart;
    var oldval = this.value;
    var newval = this.value.replace(/[^0-9.-]/g, '').replace(/^(-)|-+/g,'$1').replace(/^([^.]*\.)|\.+/g, '$1');
    this.value = newval;
    if (oldval != newval) {
        this.selectionEnd = position-1;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control rounded-pill bg-light" autocomplete="off" name="free_credit_amount" id="free_credit_amount" placeholder="Free credit amount">

Here,

  • .replace(/[^0-9.-]/g, '') - removes all chars other than digits, dots and hyphens
  • .replace(/^(-)|-+/g,'$1') - keeps the hyphen at the start of the string and removes all other hyphens
  • .replace(/^([^.]*\.)|\.+/g, '$1') - keeps any amount of text other than . and the first ., and removes all other dots in the string
like image 170
Wiktor Stribiżew Avatar answered Sep 14 '25 19:09

Wiktor Stribiżew