I need a pattern for a HTML5 form.
HTML so far
<input type="text" pattern="[a-zA-Z0-9-]" required>
The code above does not work. I guess I'm close?
You can write a JavaScript form validation script to check whether the required field(s) in the HTML form contains only letters. To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.
The validation process evaluates whether the input value is in the correct format before submitting it. For example, if we have an input field for an email address, the value must certainly contain a valid email address; it should start with a letter or a number, followed by the @ symbol, then end with a domain name.
A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty. Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity).
Unlike the regular expression syntax used in programming languages, HTML5 does not require '^' and '$' to annotate the beginning and ending of values (it is assumed). Regular expressions can be enforced on inputs by using the “pattern” attribute.
You are pretty close actually:
[a-zA-Z0-9-]+
^
You just needed this +
plus quantifier, which tells the input field to accept one or more the characters you have listed in the character class []
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With