Search code examples
javascripthtmlformsvalidationconstraints

using pattern attribute to validate value against a list of names


Is there anyway to validate an input value against a data list on client-side using pattern attribute?

for example I have an input of username and the username must be unique.

my value is

"John_Doe"

and must be validated against

[david,hello,dreamer,John_Doe,socceroos]

and it returns the form.formValidity() as false when the validation fails to fulfill the requirement?!

<input type="text" name="username"
 patern="?????">

Solution

  • pattern can accept a regular expression. In this case separate the names with "pipe" (|) which denotes "or".

    input:invalid { border: 1px solid red; }
    <input
      type="text"
      name="username"
      pattern="^(?!(david|hello|dreamer|John_Doe|socceroos)$)(\w*)"
    >