How to use the pattern attribute, to specify regular expression to input value

The pattern attribute, when specified is a regular expression which the input value must match the value of pass constraint validation it must be a valid JavaScript regular expression as used by the reg exp type.
The pattern attribute specifies a regular expression form control’s value should match. If a non-null value doesn’t conform to the constraints set by the pattern value, validity state object’s read-only patter mismatch property will be true.

<label for="username">Username: (3-16 characters)</label>
<input name="username" type="text" value="Sasha" pattern="\w{3,16}" required>

<label for="pin">PIN: (4 digits)</label>
<input name="pin" type="password" pattern="\d{4,4}" required>
The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.

<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
      type="text"
      id="uname"
      name="name"
      required
      size="45"
      pattern="[a-z]{4,8}"
      title="4 to 8 lowercase letters" />
    <span class="validity"></span>
    <p>Usernames must be lowercase and 4-8 characters in length.</p>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>

Leave a comment

Your email address will not be published. Required fields are marked *