简体   繁体   中英

Allow only positive and negative numbers in textbox using JavaScript regex

I have a textbox called count. I want to enter only positive and negative numbers in the textbox using JavaScript or jQuery regular expression. Do not allow "text" and "decimals" and "special characters" in the textbox. Even copy and paste also it should take only positive or negative numbers.

Important:

  1. If I copy and paste text or decimal or special character also it should not take. It should take only positive or negative numbers.

  2. I want to enter and paste negative values without decimal.

  3. Arrow keys should work.

  4. Shift , Ctrl , Home , End , Enter like this buttons also should work.

Please check the following fiddle and please modify this.

Fiddle

 $(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) { $(this).val($(this).val().replace(/[^\\d].+/, "")); if ((event.which < 48 || event.which > 57)) { event.preventDefault(); } });
 <span>Int</span> <input type="text" name="numeric" class='allownumericwithoutdecimal'> <div>Numeric values only allowed (Without Decimal Point) </div>

I am new for regex. Please help me for do this.

The regex you are looking for is this:

Regex: ^-?[0-9]+$

Explanation:

  • It checks for optional - ve sign. And only allows digits.

  • I have used [0-9] instead of \\d because later one means numbers in different languages.

Regex101 Demo

PS: Am not a Javascript programmer so if anyone want to add fiddle or use this regex, go ahead.

This is also achievable without regex using Javascript keypress and charCode.

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){

    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
        return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.

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