How to prevent user from entering special characters in text box when length is 0?

前端 未结 3 1787
盖世英雄少女心
盖世英雄少女心 2020-12-11 01:13

I have the following code which prevents user from entering space when the length is 0. Now, how can I prevent user from entering all special characters(anything other than

相关标签:
3条回答
  • 2020-12-11 01:36

    You can use a regex to validate the string. Something like ^[a-zA-z0-9].*

    Here is an article about testing a regex in javascript : http://www.w3schools.com/jsref/jsref_regexp_test.asp

    And you can even bind a change event and not a keypress.

    0 讨论(0)
  • 2020-12-11 01:37

    The letter and digit ranges are (inclusive):

    • 97 - 122 (a-z)
    • 65 - 90 (A-Z)
    • 48 - 57 (0-9)

    This is what you compare e.which against.

    if (e.which < 48 || 
        (e.which > 57 && e.which < 65) || 
        (e.which > 90 && e.which < 97) ||
        e.which > 122) {
        e.preventDefault();
    }
    

    Or, using inverse logic:

    var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122);
    if (!valid) {
        e.preventDefault();
    }
    

    Update

    Even so, you may still wish to validate the field contents as a whole using a regular expression:

    if (/^[A-Z0-9]+$/i.test(value)) {
        // it looks okay now
    }
    

    Or fix the field by replacing the bad stuff:

    var stripped = value.replace(/[^A-Z0-9]+/i, '');
    
    0 讨论(0)
  • 2020-12-11 01:39

    This is what you are looking for:

    $('#DivisionName').bind('keypress', function(e) {
    
        if($('#DivisionName').val().length == 0){
            var k = e.which;
            var ok = k >= 65 && k <= 90 || // A-Z
                k >= 97 && k <= 122 || // a-z
                k >= 48 && k <= 57; // 0-9
    
            if (!ok){
                e.preventDefault();
            }
        }
    }); 
    

    or see here: http://jsfiddle.net/D4dcg/

    0 讨论(0)
提交回复
热议问题