0

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

1
  • You can: if(!(totest.indexOf('test') > -1)){ // means test is not within the string } Commented Aug 24, 2018 at 13:45

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.