javascriptjqueryregex

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


Solution

  • 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,