0

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!

Tim Down
  • 318,141
  • 75
  • 454
  • 536
WEBProject
  • 1,337
  • 5
  • 16
  • 33

1 Answers1

2

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
  • 318,141
  • 75
  • 454
  • 536