2

Special characters <, >, %, '', "", $ and ^ are not allowed in a textbox. I need to put a validation check to restrict these characters on submit along with the null check.

I wrote entire validation code in a function and calling it on click of the submit button, but the function is not recognised on click.

Please help me write some JavaScript code to achieve this functionality.

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
  • You might want to post your function here. How else would people be able to tell what's wrong with it? – Tomalak May 08 '09 at 12:21
  • @Tomalak: it sounds like the function isn't the problem. It's calling it and cancelling the submit based on the results that he needs help with. The function itself could do anything. – Joel Coehoorn May 08 '09 at 13:04
  • Post how you exactly added the function to the element. – Aaron Digulla May 08 '09 at 14:42
  • http://stackoverflow.com/questions/756567/regular-expression-for-excluding-special-characters/756612 – input May 08 '09 at 12:09

5 Answers5

7

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;
   }
}
Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
Hitesh Agarwal
  • 201
  • 3
  • 4
2
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;
        }
    }
}   
Community
  • 1
  • 1
Teckie
  • 21
  • 2
2

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">
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
0
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;

}
hemc4
  • 1,623
  • 3
  • 18
  • 32
ashish
  • 1
0

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.

Roman
  • 64,384
  • 92
  • 238
  • 332