38

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.

Brandon
  • 68,708
  • 30
  • 194
  • 223
Point89
  • 455
  • 1
  • 4
  • 9

2 Answers2

91

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}">
Conor Livingston
  • 905
  • 1
  • 8
  • 17
feeela
  • 29,399
  • 7
  • 59
  • 71
  • 10
    The "required" attribute is boolean, so you can simply write "required", with no value. – Errore Fatale Apr 20 '16 at 14:10
  • 11
    Be aware that 'required' still allows the user to enter an empty string (ie. one or more spaces). See http://stackoverflow.com/questions/13766015/is-it-possible-to-configure-a-required-field-to-ignore-white-space?lq=1 – rmcsharry May 26 '16 at 16:53
  • This is showing error onpage load as well. I want something which doesn't show error on page load but only on submit – user1735921 May 27 '16 at 07:16
  • worked perfectly but is there a possibility of doing through the html pattern itself?? @feeela – pavan kumar Jul 11 '17 at 07:15
  • @pavankumar Doing what through the `pattern` attribute? – feeela Jul 11 '17 at 10:42
  • @feeela obviously to give a pattern that checks empty string.i don't want to use neither required attribute nor some javascript code – pavan kumar Jul 11 '17 at 12:36
  • `a b` is invalid, any trick to make this valid? like `trim()` in JS? – l2aelba Jul 26 '18 at 08:36
  • @feeela you can use PHP ValueObject to check whether an empty string has been passed. Just implement __toString() to use the ValueObject directly like a string variable later, and check in constructor if " " was passed – clockw0rk Aug 20 '20 at 09:03
  • @clockw0rk If at some point a combination of `trim` and `empty` is not sufficient anymore, I might do so… – feeela Aug 20 '20 at 13:31
3

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,}">
simhumileco
  • 31,877
  • 16
  • 137
  • 115
Patrick Kenekayoro
  • 326
  • 1
  • 3
  • 10