开发者

How do I only allow a user enter "-" and 1-9 into the textbox?

开发者 https://www.devze.com 2023-02-21 03:16 出处:网络
How do I only allow a u开发者_如何学Cser enter \"-\" and 1-9into the textbox using onkeyup?With jQuery

How do I only allow a u开发者_如何学Cser enter "-" and 1-9 into the textbox using onkeyup?


With jQuery

Update: I saw the other answers using jQuery and assumed you had jQuery. Read through below for notes, and then see below for the non jQuery versions.

Also, my example uses \d which allows 0 as well (your question explicitly states 1-9). If you really do want to limit 1-9, swap \d with 1-9.

Example 1

You could just strip the non valid characters on keyup.

$('textarea').keyup(function() {
    $(this).val(function(index, oldVal) {
        return oldVal.replace(/[^\d-]/g, '');
    });
});

jsFiddle.

You may also want to bind other events, such as paste.

Example 2

If the character displaying momentarily is annoying you, you could use this...

$('textarea').keypress(function(event) {
    var keyCode = event.keyCode;
    if ( ! (keyCode >= 48 && keyCode <= 57) && keyCode != 45) {
          event.preventDefault();
    }
});

jsFiddle.

Example 3

If that is too difficult to read (with key codes), you could do this...

$('textarea').keypress(function(event) {
    if ( ! String.fromCharCode(event.keyCode).match(/[\d-]/)) {
          event.preventDefault();
    }
});

jsFiddle.

Also, when browsers finally catch up to the spec, you could use the pattern attribute with [\d-]+. This will only allow 0-9 and -.


JavaScript

Example 1

var textareas = document.getElementsByTagName('textarea');
for (var i = 0, textareasLength = textareas.length; i < textareasLength; i++) {
    var textarea = textareas[i];
    textarea.onkeyup = function() {
        textarea.value = textarea.value.replace(/[^\d-]/g, '');
    }
}

jsFiddle.

Example 2

var textareas = document.getElementsByTagName('textarea');
for (var i = 0, textareasLength = textareas.length; i < textareasLength; i++) {
    var textarea = textareas[i];
    textarea.onkeypress = function(event) {
        var keyCode = event.keyCode || event.which;
        if (!(keyCode >= 48 && keyCode <= 57) && keyCode != 45) {
            event.preventDefault();
        }
    }
}

jsFiddle.

Example 3

var textareas = document.getElementsByTagName('textarea');
for (var i = 0, textareasLength = textareas.length; i < textareasLength; i++) {
    var textarea = textareas[i];
    textarea.onkeypress = function(event) {
        var keyCode = event.keyCode || event.which;
        if (!String.fromCharCode(event.keyCode).match(/[\d-]/)) {
            event.preventDefault();
        }
    }
}

jsFiddle.


If you are using jQuery:

var isAcceptableKey = /[0-9,-]*/;

$(yourinput).bind('keyup', function(e) {
  if ( e.keyCode.match(isAcceptableKey) {
    // ok
  }
});

As one of the comments pointed out. just use regex. My regex example probably isn't exactly right though.


Here is a solution which blocks all non numeric input from being entered into the text-field, excluding the '-' character from both top row of numeric inputs and the keypad on the side.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    if (!((k > 47 && k < 58) || (k > 95 && k < 106)) && !(k == 189 || k == 109 || k == 8 || k == 46)) {
        e.preventDefault();
        return false;
    }
};​


Do you mean only a positive or negative integer?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

try something like:

if(isNaN(parseInt(textbox.value)))
{
  //this is a validation error.
}

otherwise something like:

var validationRegex = RegExp(/[-0-9]+/, "g");
if(!validationRegex.match(textbox.value)
{
  //this is a validation error.
}

Disclamer: I haven't tested these.

put them in a function

function doKeyUpValidation(textbox)
{

}

and either markup:

<input type="text" onkeyup="doKeyUpValidation(this)" />

or javascript:

textbox1.onkeyup = function (){...}


As you can from the posted answer there are many ways of doing this.

I have also other way of doing this. See below code

JS

function isValidChar(char){

    var txt = char;
    var found = false;
    var validChars = "-123456789"; //List of valid characters

    for(j=0;j<txt.length;j++){ //Will look through the value of text
        var c = txt.charAt(j);
        found = false;
        for(x=0;x<validChars.length;x++){
            if(c==validChars.charAt(x)){
                found=true;
                break;
            }
        }
        if(!found){
            //If invalid character is found remove it and return the valid character(s).
            document.getElementById('txtFld').value = char.substring(0, char.length -1);
            break;
        }
    }
}

And in your html:

<input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />

Well actually my superior is the one who did this. My point is by using this you can play on the code and insert what other things you may need. Example if you are not knowledgeable in regular expression you can just simply type the characters. Well downside is, the code eat much space rather than using a jquery that the other did here.

0

精彩评论

暂无评论...
验证码 换一张
取 消