Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML simple not blank pattern

Tags:

html

regex

I have a simple form and i want the submit button not to work for the conditions i give in the pattern, but if i leave it blank the submit works. how can i make the pattern not to accept it if it is blank?

<form action="test.php" method="POST"> Enter user name:  <input type="text" name="username" pattern="[A-Za-z0-9]{1,20}"> <input type="submit" value="submit"> </form> 

I thought the {1,20} is enought but it seems it's not.

like image 777
Point89 Avatar asked Nov 02 '12 16:11

Point89


People also ask

How do I create a pattern in HTML?

The pattern attribute specifies a regular expression that the <input> element's value is checked against on form submission. Note: The pattern attribute works with the following input types: text, date, search, url, tel, email, and password. Tip: Use the global title attribute to describe the pattern to help the user.

Can we use RegEx in HTML?

While arbitrary HTML with only a regex is impossible, it's sometimes appropriate to use them for parsing a limited, known set of HTML. If you have a small set of HTML pages that you want to scrape data from and then stuff into a database, regexes might work fine.

What is pattern tag in HTML?

The pattern attribute is an attribute of the text, tel, email, url, password, and search input types. The pattern attribute, when specified, is a regular expression which the input's value must match in order for the value to pass constraint validation.


2 Answers

HTML has the required attribute to accomplish this. If you set any input to be required, modern browsers won't let you submit the form if those fields are empty.

<input type="text" name="username" required="required" pattern="[A-Za-z0-9]{1,20}"> 
like image 75
feeela Avatar answered Sep 19 '22 11:09

feeela


To prevent errors from showing on load, you can not use the HTML5 required attribute. You can use JavaScript. For example:

if ( $('#form-password').val() === "" )  {     e.preventDefault(); } 

Using HTML Patterns to match at least one:

<input type="text" name="username" pattern=".{1,}"> 
like image 37
Patrick Kenekayoro Avatar answered Sep 19 '22 11:09

Patrick Kenekayoro