简体   繁体   中英

Allow only numbers and underscore(_) using jQuery

I need to have a valid input like this 122_123 . If the entered id is wrong I need to display an error message. This has to be done using jQuery. I have the below code which doesn't seem to work for some reason.

$('[id*=search]').unbind().click(function() {
    var numPattern = /^[0-9_]+$/;
    //check if the copy pasted value of RequestId has alphabets.
    if (!(/^[_0-9]*$/i).test($('[id*=reqId]').val()){
        alert('Invalid');
        $('[id*=reqId]').val('');
        return false;
    }
    displaySpinner();
    return true;
});

What would be the best way to solve this?

What i think you are actually checking for opposite of .test() . You should remove the ! not sign from the condition:

if ((/^[_0-9]*$/i).test($('[id*=reqId]').val()){

Check you this may help you :--

 $('document').ready(function() { $('#input_id').bind('keyup', function(e) { console.log($('#input_id').val()); if ((/[_0-9]$/i).test($('#input_id').val())) { $('p').html("true"); } else { $('p').html("false"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input id="input_id" type="text" /> <p></p> 

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