views:

31

answers:

1

Hi,

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-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!

+2  A: 

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;
}
Tim Down
This regex doesn't allow spaces, which the OP said he wanted.
Brock Adams
So he did, I missed that. Though I think the OP did edit the question to make that clearer after I'd started writing my answer. Anyway, fixed now.
Tim Down
@Tim: you don't need to escape dots or quantifiers inside the character class
SilentGhost
However, you *do* need to escape hyphens if they're in the middle (like they are here - the range `+-=` means `<` will be incorrectly included).
Peter Boughton
SilentGhost, Peter: good points, thanks. Also, there's no need to escape parentheses inside a character class. Fixed now.
Tim Down