不要允许特殊字符jQuery

时间:2013-08-05 06:39:11

标签: javascript jquery logic

有一些错误,请你们告诉我我做错了什么

function verifyGroup(groupVal, errorid) {

    groupVal = $.trim(groupVal);

    if (groupVal != '') {

        var splChars = "*|,\":<>[]{}`\';()@&$#%!+-";
        for (var i = 0; i < groupVal.length; i++) {
            console.log(groupVal.charAt(i)+' == '+splChars.indexOf(groupVal.charAt(i)));

            if (splChars.indexOf(groupVal.charAt(i)) != -1) {

                $("#" + errorid).addClass("form-error").html("Illegal characters detected!");
                return false;
            } else {
                $("#" + errorid).removeClass("form-error").html("");
                return true;
            }
        }
    } else {
        $("#" + errorid).addClass("form-error").html("Group name should not be empty");
        return false;
    }
}

DEMO

2 个答案:

答案 0 :(得分:1)

使用正则表达式

function verifyGroup(groupVal, errorid) {

    groupVal = $.trim(groupVal);
    console.log(groupVal);
    console.log(errorid);
    if (groupVal != '') {

        var regex = /[*|,\\":<>\[\]{}`';()@&$#%!+-]/;
        if(regex.test(groupVal)){
            $("#" + errorid).addClass("form-error").html("Illegal characters detected!");
            return false;
        } else {
            $("#" + errorid).removeClass("form-error").html("valid");
            return true;
        }
    } else {
        $("#" + errorid).addClass("form-error").html("Group name should not be empty");
        return false;
    }
}
$(function() {
    // Handler for .ready() called.

    $('#submit').click(function(){
        verifyGroup($('#ipId_create').val(), 'error_id');
    });
});

演示:Fiddle

答案 1 :(得分:0)

-1的比较应为==而不是!=