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.
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.
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.
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.
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}">
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,}">
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