Validating with Regular Expressions

Making a field required is an easy way to ensure that the user does not leave the field blank. But what if you want to be specific about what should go into a field? This kind of validation calls for the pattern attribute.

After the required attribute on your order <input>, add a pattern attribute. Assign it a specially formatted string called a regular expression, which we will explain in a moment.

...
            <div class="form-group">
              <label for="coffeeOrder">Order</label>
              <input class="form-control" name="coffee" id="coffeeOrder"
                autofocus required pattern="[a-zA-Zs]+" />
            </div>
...

A regular expression is a sequence of characters for pattern matching. The regular expression [a-zA-Zs]+ matches any character from the set consisting of lowercase letters (a-z), uppercase letters (A-Z), and whitespace characters (s), repeated one or more times (+).

In short, when you submit the form this field will only be valid if it contains letters or spaces.

Save and reload. See what happens if you put symbols or numbers into the order field and try to submit the form.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.253.210