dmid
dmid

Reputation: 493

html5 validation - valid when the value is NOT equal to a certain string

I have an html input that is required and I am setting a pattern on the input dynamically using jQuery, like this:

let theString = 'test'

$('input[name="string"]').attr("pattern", theString)

this works fine, the input is only valid when its value is exactly equal to: test

How can I do the reverse of this? I would like it only to be valid if the value is anything other than: test

Upvotes: 0

Views: 1251

Answers (1)

Gary Thomas
Gary Thomas

Reputation: 2331

We can use a negative lookahead to reverse this regex. Bare in mind there are still very simple ways around this, and you should rely on a backend validation rather than a frontend validation when submitting forms.

<form>
    <input type="text" name="string" required/>
    <button type="submit">Submit</button>
</form>

<script>
    $(function() {
        let theString = '^(?!test$).*';

        $('input[name="string"]').attr("pattern", theString);
    });
</script>

Upvotes: 2

Related Questions