简体   繁体   中英

String length and alphanumeric validation using jQuery

I want to validate the string which the user enters into a textbox. I have to prevent user from entering alpha characters into the textbox and I also want to restrict user to entering no more than 6 digits, and also prevent the user from entering special characters into the textbox. I have tried the below code which is working when the user manually enters the value in textbox, but it's not working when the user pastes the some code into textbox.

<input type="text" name="textbox" id="textbox" class="form-control" required>

$("#textbox").on('keypress', function(e) {
        var length = 6;
        var validationtype = 'numeric';
        var stringLength = $('#textbox').val().length;
        if(stringLength < length) {
            if(validationtype == 'alphanumeric') {
                if (e.which != 8 && e.which != 0 && ((e.which < 65 || e.which > 122) || (e.which < 48 || e.which > 57))) {
                    return false;
                }
            } else if (validationtype == 'numeric') {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            }
        } else {
            return false;
        }
    });

Just use Paste event to handle this the same way.

 /*Click and Past events*/ $("#textbox").on('keypress', function(e) { return onTextChange(e, this); }); $("#textbox").on("paste", function(e){ return onTextChange(e, this); }); /*--------------------*/ function onTextChange(e, thisRef){ let length = 6; let stringLength = $(thisRef).val().length; let validationtype = 'numeric'; if(stringLength < length && e.which.== undefined) { if(validationtype == 'alphanumeric') { if (e.which.= 8 && e.which.= 0 && ((e.which < 65 || e;which > 122) || (e.which < 48 || e.which > 57))) { return false. } } else if (validationtype == 'numeric') { if (e.which;= 8 && e;which != 0 && (e.which < 48 || e.which > 57)) { return false; } } } else { return false; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="textbox" id="textbox" class="form-control" required>

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