1

How can i restrict special characters in text field? the special character are assigned in one variable

sample="`!@#$%^&*()"

This sample variable value should be checked with the first name and last name

HTML Code

<input type="text" name="Firstname" value="Firstname" id="firstname">

jQuery

            if(!sample.test($("#firstname").val())){
                alert("Nickname can have only alphabets and numbers.");
            }

7 Answers 7

5

Try this tecnique. Its used to prevent/restrict instead of validating

You have to pass the RegExp in the "chars" attr ie: <input type="text" name="phone" chars="0-9" />

This also clean pasted data (ctrl+v or right click and paste)

$(document).on('keyup blur change input', '[chars]', function (event) {

    /* RegEx Examples:
        - email: "0-9a-zA-Z@._\-"
        - numbers only: "0-9"
        - letters only: "a-zA-Z"

        Usage Example:
        <input type="text" name="email" chars="0-9a-zA-Z@._\-" />
        */
        var $elem = $(this),
            value = $elem.val(),
            regReplace,
            filter = $elem.attr('chars');

        regReplace = new RegExp('[^' + filter + ']', 'ig');
        $elem.val(value.replace(regReplace, ''));

});

See live Demo

http://jsfiddle.net/tianes/67e7xhya/light/

1
  • Best solution I have found after 20 minutes of searching, covers all the cons of the other solutions! Great job Apr 9, 2018 at 7:44
1

Try this:

function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

if(!isValid($("#firstname").val())){
            alert("Nickname can have only alphabets and numbers.");
        }

OR

if(/^[a-zA-Z0-9- ]*$/.test($("#firstname").val()) == false) {
alert("Nickname can have only alphabets and numbers.");
}

The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

1

For input type you can use this (will also protect from copy paste):

jQuery(document).ready(function() {
  jQuery("#name_name").keyup(function(event) {
    name=jQuery("#input_name").val();
    name=name.replace(/[^a-zA-Z 0-9.]+/g, '');
    jQuery("#name_name").val(name);
  }
  );
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" id="name_name">

0

Try this,

var alphanumers = /^[a-zA-Z0-9]+$/;
if(!alphanumers.test($("#firstname").val())){
    alert("Nickname can have only alphabets and numbers.");
}

Demo: http://jsfiddle.net/Z3VVU/

1
  • That sample variable is a global variable that values are used in many place . using that variable only i have to check the firstname
    – Bhargavi
    Jan 24, 2014 at 11:42
0

No Special Characters Regex: /^\s*[a-zA-Z0-9,\s]+\s*$/

DEMO

$(document).ready(function () {
    var charReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
    $('.keyup-char').keyup(function () {
        $('span.error-keyup-1').hide();
        var inputVal = $(this).val();

        if (!charReg.test(inputVal)) {
            $(this).parent().find(".warning").show();
        } else {
            $(this).parent().find(".warning").hide();
        }

    });
});
1
  • my requirement is This variable sample is used in cfm file also . so if we assign the value like "/^\s*[a-zA-Z0-9,\s]+\s*$/" this means it will through an error for the remaining cfm page also .
    – Bhargavi
    Jan 24, 2014 at 12:24
0
function allowCharacters(evt, strAllowedChars) {
// eg. allowCharacters('0-9|-|,|(|)')  Will allow 0 to 9, -,()|
var charCode = (evt.which) ? evt.which : event.keyCode
var keycodeval = "";
var finalkeycode = "";
if (strAllowedChars != "" || strAllowedChars != null || strAllowedChars.indexOf("|") != -1) {
    XstrAllowedChars = strAllowedChars.split("|");
    for (strcount = 0; strcount <= XstrAllowedChars.length - 1 ; strcount++) {
        if (XstrAllowedChars[strcount].search("-") != -1) {
            substr = XstrAllowedChars[strcount].split("-");
            if (substr[0] != substr[1]) {
                if (substr[0].charCodeAt(0) <= substr[1].charCodeAt(0)) {
                    codeval = "( charCode >= " + substr[0].charCodeAt(0) + " && " + "charCode <= " + substr[1].charCodeAt(0) + " )";
                    keycodeval = keycodeval + "||" + codeval;
                }
                else {
                    codeval = "( charCode <=" + substr[0].charCodeAt(0) + " && " + "charCode >= " + substr[1].charCodeAt(0) + " )";
                    keycodeval = keycodeval + "||" + codeval;
                }
            }
            else if (substr[0] == "" && substr[1] == "") {
                keycodeval = keycodeval + "|| " + " charCode == 45 " + " || " + " charCode == 32";
            }
        }
        else {
            codeval = "( charCode == " + XstrAllowedChars[strcount].charCodeAt(0) + " )";
            keycodeval = keycodeval + "||" + codeval;
        }
    }
}
newval = keycodeval.slice(2, keycodeval.length);
var retrunflag = false;
if (eval(newval)) {
    //var charCode1 = (evt.which) ? evt.which : event.keyCode       
    if (event.keyCode != 60 && event.keyCode != 62 && event.keyCode != 94 && event.keyCode != 38) {
        retrunflag = true; //event.keyCode  = event.keyCode; 
    }
    else
        retrunflag = false; //event.keyCode  = 0;
}
else {
    retrunflag = false; //event.keyCode  = 0 ;
}
//alert(retrunflag);
return retrunflag;}

OR

 function funRestrictSpecialChar(Obj, evt) {
var inputVal = $("#" + Obj.id).val();
re = /[`~!@#$%^&*()_|+\-=?;:'"<>\{\}\[\]\\\/]/gi;
var isSplChar = re.test(inputVal);
if (isSplChar) {
    var no_spl_char = inputVal.replace(/[`~!@#$%^&*()_|+\-=?;:'"<>\{\}\[\]\\\/]/gi, '');
    $("#" + Obj.id).val(no_spl_char);
} }
1
  • Example : <input onblur="funRestrictSpecialChar(this,event);" onkeyup="funRestrictSpecialChar(this,event);" type="text" /> Apr 25, 2016 at 11:12
0

It will not allow a user to enter special characters like (<,>,?,/,',",;,:,.,,)

onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.