regex except alphanumeric validation

Regex except alphanumeric validation

Regular expressions or regex are a powerful tool in web development when it comes to validating user inputs. However, sometimes we need to validate user inputs that should not contain alphanumeric characters. In this scenario, we can use a regex except alphanumeric validation to ensure that the input conforms to our requirements.

Method 1: Using Character Classes

One way to achieve this is by using character classes in regular expressions. Character classes allow us to define a set of characters that we want to match or exclude from matching. In our case, we want to exclude alphanumeric characters.


<div>
    <form action="#" method="post">
        <label for="input">Enter non-alphanumeric string:</label>
        <input type="text" id="input" name="input" pattern="[^a-zA-Z0-9]+" required>
        <input type="submit" value="Submit">
    </form>
</div>

In the example above, we have used the pattern attribute with the value [^a-zA-Z0-9]+. The caret (^) symbol inside the square brackets means "not". Therefore, the regex will match any character that is not an uppercase or lowercase letter (a-z, A-Z) or a digit (0-9). The plus (+) symbol means that we want to match one or more occurrences of the preceding character class.

Method 2: Using Negative Lookahead

Another way to achieve the same result is by using negative lookahead in regular expressions. Negative lookahead allows us to assert that a certain pattern does not exist ahead of the current position in the string.


<div>
    <form action="#" method="post">
        <label for="input">Enter non-alphanumeric string:</label>
        <input type="text" id="input" name="input" pattern="^(?![A-Za-z0-9]+$).+" required>
        <input type="submit" value="Submit">
    </form>
</div>

In the example above, we have used the pattern attribute with the value ^(?! [A-Za-z0-9]+$).+. The caret (^) symbol outside the parentheses means that the regex should match from the beginning of the string. The negative lookahead (?![A-Za-z0-9]+$) inside the parentheses asserts that the string should not contain only uppercase or lowercase letters (a-z, A-Z) or digits (0-9). The plus (+) symbol outside the parentheses means that we want to match one or more occurrences of any character.

Both of these methods essentially achieve the same thing, and which one to use is a matter of personal preference. However, it's important to note that using character classes can be more performant than using negative lookahead, especially for larger strings.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe