Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 input validate letters and numbers

Tags:

html

regex

forms

I need a pattern for a HTML5 form.

  • Lowercase letters accepted
  • Uppercase letters accepted
  • Numbers accepted
  • Minus character accepted

HTML so far

<input type="text" pattern="[a-zA-Z0-9-]" required>

The code above does not work. I guess I'm close?

like image 889
Jens Törnell Avatar asked Nov 29 '13 14:11

Jens Törnell


People also ask

How do I validate only alphabets in HTML?

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.

How do you validate a name field in HTML?

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.

How do you validate numbers in HTML?

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).

Can you use regular expressions with HTML5 inputs?

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.


1 Answers

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 [].

like image 74
Ibrahim Najjar Avatar answered Jan 04 '23 02:01

Ibrahim Najjar