开发者

Check if specific chars were written and trigger an error

Im trying to figure out via JS if invalid chars were entered in a textarea

I want to allow only this chars:

A-Za-z0-开发者_JAVA百科9 !#%&*()+-=,.?"';:/

If illegal chars were entered, I want to retrieve the bad chars, and trigger an error, i.e:

Invalid text, bad chars were written:

1) _
2) @
etc...

Thanks!


I'm not sure when you want to do this check, but here's a function to do the checking. It will alert the first non-valid character.

function checkValue(input) {
    var result = /[^a-z0-9 !#%&*()+\-=,.?"';:\/]/i.exec(input.value);
    if (result) {
        alert("Character '" + result[0] + "' is not allowed");
        return false;
    } else {
        return true;
    }
}

If you want all the matched non-valid characters, then you could use the following:

function checkValue(input) {
    var isValid = true, result, matchedChars = [];
    while( (result = /[^a-z0-9 !#%&*()+\-=,.?"';:\/]/ig.exec(input.value)) ) {
        matchedChars.push("'" + result[0] + "'");
        isValid = false;
    }
    if (!isValid) {
        alert("Characters " + matchedChars.join(", ") + " are not allowed");
    }
    return isValid;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜