使用jQuery限制特殊字符

rslzwgfq  于 2022-12-29  发布在  jQuery
关注(0)|答案(7)|浏览(177)

如何限制文本字段中的特殊字符?特殊字符被分配到一个变量中

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

应检查此示例变量值的名字和姓氏
HTML代码

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

jQuery语言

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

ovfsdjhp1#

尝试此技术。它用于防止/限制而不是验证
必须在“chars”属性中传递RegExp:第一个月
这也会清除粘贴的数据(ctrl+v或右键单击并粘贴)

$(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, ''));

});

观看现场演示
http://jsfiddle.net/tianes/67e7xhya/light/

ve7v8dk2

ve7v8dk22#

试试这个:

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

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

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

上面只允许字符串完全由a-z,A-Z,0-9范围内的字符加上连字符和空格字符组成。包含任何其他字符的字符串将导致alert

qlzsbp2j

qlzsbp2j3#

对于输入类型,您可以使用此选项(也可以防止复制粘贴):

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">
n6lpvg4x

n6lpvg4x4#

试试这个

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

演示:http://jsfiddle.net/Z3VVU/

swvgeqrz

swvgeqrz5#

无特殊字符正则表达式:第一个月
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();
        }

    });
});
7y4bm7vi

7y4bm7vi6#

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;}

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);
} }
ymdaylpp

ymdaylpp7#

它不允许用户输入特殊字符,如(〈、〉、?、/、'、"、;,:,.,,)

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

相关问题