0

I need to validate a code format:

  1. Need to be 10 characters
  2. A mix of letters and numbers
  3. At least 1 letter from a-f

and I write:

<input maxlength="200" type="text" name="code" id="code" required="required" class="form-control input-lg"  pattern="[a-fA-F0-9]{10}" title="Wrong Code" placeholder="Security Code" />

so my pattern is pattern="[a-fA-F0-9]{10}" but HOW I can add rules that at least 1 letter from a-f is required?

Aleks Per
  • 1,549
  • 7
  • 33
  • 68

4 Answers4

2

You could use a positive lookahead (?= to assert that what follows contains at least 1 occurance of [a-fA-F]

Updated version suggested by Wiktor Stribiżew

(?=[0-9]*[a-fA-F])[a-fA-F0-9]{10}

Explanation about the positive lookahead (?=[0-9]*[a-fA-F])

  • (?: Non capturing group
    • [0-9]* Match zero or more times a digit
    • [a-fA-F] Match a-f in lower or uppercase
  • ) Close non capturing group

<form>
  <input maxlength="200" type="text" name="code" id="code" required="required" class="form-control input-lg" pattern="(?=[0-9]*[a-fA-F])[a-fA-F0-9]{10}" title="Wrong Code" placeholder="Security Code" />
  <input type="submit" name="submit">
</form>
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

Regex pattern to match at least 1 number and 1 character in a string

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

Look at the regex in this thread, it should fit your needs. You need to replace your pattern with it.

Lumpenstein
  • 1,250
  • 1
  • 10
  • 27
0

try this one

<form action="/action_page.php">
  <input type="text" name="code" id="code" required="required" class="form-control input-lg" pattern="(?=[a-fA-F0-9]*[a-fA-F])[a-fA-F0-9]{10}" title="Wrong Code" placeholder="Security Code" />
  <input type="submit">
</form>

<b>
<pre>
1)Need to be 10 characters
2)A mix of letters and numbers
3)At least 1 letter from a-f
</pre></b>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

There is already an accepted answer, but that one is not complete.

The requirements state that there needs to be "A mix of letters and numbers" and "At least 1 letter from a-f". That would mean that these entries below would match as well:

8adfl9542a
m0ammmmmmm
11111a1111

They do not match in the accepted answer. I created my own regex which shows that the above entries match as well:

(?=.*[a-fA-F]+)(?=.*[0-9]+)[a-zA-Z0-9]{10}

Explanation:

(?=.*[a-fA-F]+) Match at least one character from a-f (upper- or lowercase)

(?=.*[0-9]+) Match at least one number

[a-zA-Z0-9]{10} Total string must be 10 characters long and must consist of characters from a-z (upper- or lowercase) or numbers

Starfish
  • 3,344
  • 1
  • 19
  • 47