1

I have a <input type="email"/> and want it to
a) be a valid email address and
b) be something other than a given email address - let's say "root@localhost".

I had a look into the Pattern for HTML input elements and now I try to write a pattern excludes a specific value.

I stumbled across this Post: A regular expression to exclude a word/string and looked into negative look ahead, which was quite promising. Except for one thing:
If I use negative lookahead, it will also match anything that starts with the given exlusion, not only those that exactly match it!

My Code:

<input type="email" name="email" pattern="^(?!root@localhost).+$" required>

This will result in a validation error for

  • empty text (correct)
  • non-email-texts (correct)
  • an email-address of "root@localhost" (correct)
  • any email addresss starting with "root@localhost" (wrong)

Can you please help me on how to write a pattern that excludes exactly one email address from the validation?

Is using a pattern the right way here?

Thanks,
Alexander

Alexander
  • 2,925
  • 3
  • 33
  • 36
  • 3
    Use `pattern="^(?!root@localhost$).*$"` or just `pattern="(?!root@localhost$).*"` since it is anchored by default. – Wiktor Stribiżew Nov 14 '18 at 16:30
  • @WiktorStribiżew looks like you're right. `pattern="(?!root@localhost$).*` seems to work. Feel free to post it as an answer and I'll accept it – Alexander Nov 14 '18 at 16:36

2 Answers2

1

You may use

pattern="(?!root@localhost$).*"

Since the HTML5 patterns are anchored at both ends automatically you don't have to enclose the pattern with ^ and $.

The overall regex after HTML5 engine processes the attribute value will look like /^(?:(?!root@localhost$).*)$/ (in FF and Chrome, it will be compiled with u flag) and will match any 0 or more chars other than line break chars, from the start till the end of a string, that is not equal to root@localhost string.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Why not use javascript validation

function validate(form) {
    if (form.email === "root@localhost") {
        return false;
    }

    return /.+\@.+\..+/.test(form.email);
}
Nikhil Ranjan
  • 994
  • 12
  • 16
  • there are reasons for that. Pattern is an elegant way to perform a validation on any input field where no piece of Javascript needs to be written. – Alexander Nov 14 '18 at 16:36