Special character validation using JavaScript

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

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

相关标签:
5条回答
  • 2021-01-15 03:14

    A much simpler way is to use indexOf in javascript,

    function isSpclChar(){
       var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
       if(document.qfrm.q.value.indexOf(iChars) != -1) {
         alert ("The box has special characters. \nThese are not allowed.\n");
         return false;
       }
    }
    
    0 讨论(0)
  • 2021-01-15 03:20
    function isSpclChar(){
    var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    for (var i = 0; i < document.qfrm.q.value.length; i++) {
        if (iChars.indexOf(document.qfrm.q.value.charAt(i)) != -1) {
        alert ("The box has special characters. \nThese are not allowed.\n");
        return false;
            }
        }
    }   
    
    0 讨论(0)
  • 2021-01-15 03:20

    Try something like

    <form ... onsubmit="function()">
    

    In function you can get text from your textarea or what you are using. If data is valid function () should return true. Otherwise form wouldn't be submitted.

    0 讨论(0)
  • 2021-01-15 03:36
    function alphanumeric_only(event)
     {
        var keycode;
    
       keycode=event.keyCode?event.keyCode:event.which;
    
    
       if ((keycode == 32) || (keycode >= 47 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122)) {
    
            return true;
    
        }
    
        else {
            alert("Sorry You can not insert Special Character");
            return false;
    
        }
        return true;
    
    }
    
    0 讨论(0)
  • 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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Enter something here : <input id="text">

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