Alphanumeric validation error not working

Viewed 12

I am using below jquery to validate a textbox

 $(document).on("change keypress", ".alphabets-numbers", function (e) {
    
    var regex = new RegExp("^[a-zA-Z0-9_-]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (!regex.test(str)) {
        swal({
            title: "Input Warning",
            type: "warning",
            text: "Only alphabets, numbers '-' and '_' are allowed"
        });

        return false;
    }
});

The above validation works fine when user enters non alpha numeric characters but when user enter numbers only and then textbox focus is out the validation message popup gets displayed. I want it should accept only numbers also. Please help!!!

0 Answers
Related