Search code examples
javascriptregexvalidationtextboxwhitelist

Javascript textbox - do not submit with non-whitelist characters


I have a textbox that sends text to a div when I hit return or click a button. I need to exclude strings and give an error message that have characters that aren't on my whitelist. I was hoping I could check the string when the user submits the text instead of checking each character as they type.

I've tried going the Regular Expression test route but it returns true if any character matches my whitelist, not if every character matches. (Code only has letters on my whitelist, but I can change that part later by myself.)

        function valTxt(x) {
            var patt=/[a-z]/i;
            if (patt.test(x)) {
                document.getElementById("valMsg").innerHTML = "Contains letters.";
            }
            else {
                document.getElementById("valMsg").innerHTML = "Does not contain letters.";
            }
        }

Do I need to use a loop to check each character, or is there a predefined function or method that does what I want to do?


Solution

  • You just need the start and end anchors on your regex. That tells it 0 or more characters between start and end must be of your whitelist

    function valTxt(x) {
            var patt=/^([a-zA-Z])*$/;
            if (patt.test(x)) {
                // matched
            } else {
                // didn't match
            }
    }