using pattern attribute to validate value against a list of names

Viewed 38

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="?????">
3 Answers

Use regexp alternatives:

pattern="david|hello|dreamer|John_Doe|socceroos"

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*)"
>

I am using a regex to validate my username. I have no idea if it's standard or not! But working very well for me: first, when you send a get request, you need to get all your usernames and make a touchups and then pass your currentUsername variable defined on your controller to be used on your html file using ejs npm:

for (let i = 0; i < usernames.length; i++) {
    usernames[i] = ("^" + usernames[i] + "$|");
    if (i === usernames.length - 1) {
        usernames[i] = usernames[i].slice(0, -1)
    }
};
const currentUsernames = usernames.reduce((a, b) => a + b);

And use the following pattern as your element attribute:

patern="(?!<%= currentUsernames %>).*"
Related