-3

I need to Allow only numbers and special character minus "-" to be typed in a textbox, plz help me i already have a number restriction, but wanna minus sign too.

thanks in advance

<script>
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
</script>


<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
jai
  • 3
  • 1
  • 4

2 Answers2

0

This regex will check for numbers and '-'. If there are other characters, they'll be replaced.

$('.input').keyup(function () {
    if (!this.value.match(/^(\d|-)+$/)) {
        this.value = this.value.replace(/[^0-9-]/g, '');
    }
});

No jQuery version:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyup="isNumber()" />

function isNumber() {
    var inputField = document.getElementById('extra7');
    if (!inputField.value.match(/^(\d|-)+$/)) {
        inputField.value = inputField.value.replace(/[^0-9-]/g, '');
    }
}
peterulb
  • 2,869
  • 13
  • 20
0

Adding !=45 is not sufficient. You need to prevent the acceptance of invalid key inputs too. Returning true/false will still allow user to type those keys and your code then will seem to do nothing.

if ((charCode < 48 || charCode > 57) && charCode != 45) {
   evt.preventDefault();
}

This way only valid key inputs will appear in text box.

Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32