Special character validation using JavaScript

前端 未结 5 1615
不思量自难忘°
不思量自难忘° 2021-01-15 02:48

Special characters <, >, %, \'\', \"\", $ and ^ are not allowed in a textbo

5条回答
  •  庸人自扰
    2021-01-15 03:39

    Try this:

    $('#text').keypress(function (e) {
        validationForSpecialchar(e); 		        
    });
    
    function validationForSpecialchar(e){
        var regex = new RegExp("^[a-zA-Z0-9-]+$"); 
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        e.preventDefault();
        return false;
    }
    
    Enter something here : 

提交回复
热议问题