0

I don't understand why my Regex doesn't work. There is always an error message for any passwords.

 $this->add('password', new RegexValidator(array(
           'pattern' => '.{0}|.{4,}',
           'message' => '0 or 4 char minimum'
 )));

The error is : 0 or 4 char minimum.

John
  • 4,711
  • 9
  • 51
  • 101
  • 1
    What, exactly, is the error message? – Fish Below the Ice Sep 04 '15 at 12:40
  • this : 0 or 4 char minimum. This is my message – John Sep 04 '15 at 12:45
  • That's important information that should be in your question. Comments are meant to be temporary. Please [edit] your question. – Fish Below the Ice Sep 04 '15 at 12:46
  • From what I can tell your regular expression is invalid, so it is always failing. What do you want the regex to validation - between 0 and 4 characters? – Jason McCreary Sep 04 '15 at 12:47
  • I need the same things than http://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html5 – John Sep 04 '15 at 12:51
  • Then do not use `required` (and it will be allowed to be empty), and use `pattern=".{4,}"`. Does it work then? – Wiktor Stribiżew Sep 04 '15 at 12:52
  • I know that. It's ok for my view side. But now I'm doing a validation server side with Phalcon. And this Regex doesn't work. I don't know why the regex works well in my view and doesn't work with Phalcon regex Phalcon\Mvc\Model\Validator\Regex – John Sep 04 '15 at 12:54
  • 1
    You don't need a regex for this, `empty` and `strlen` could accomplish this and would probably be easier to read. – chris85 Sep 04 '15 at 12:58
  • @chris85 I'm using Phalcon PHP so I have to use the "validator" class. And I can't use PresenceOf() and StringLength() class because I need to validate the password if he is nul or if this length is >= 4 – John Sep 04 '15 at 13:04

1 Answers1

1

Just combine the StringLenght validation with the allowEmpty option:

$badPassMessage = 'Define a password using exactly 4 characters or leave it empty!';
$validation->add('password', new StringLength(array(
      'max' => 4,
      'min' => 4,
      'allowEmpty' => true,
      'messageMaximum' => $badPassMessage,
      'messageMinimum' => $badPassMessage
)));
BONUS

I'd recommend you to always test your patterns with this excellent tool:

regular expressions 101

Always make sure that the regex flavor is set to pcre (php).

cvsguimaraes
  • 12,910
  • 9
  • 49
  • 73
  • Oh awesome. The allowEmpty parameter is the solution. So now I can use the StringLenght validation https://docs.phalconphp.com/en/latest/api/Phalcon_Validation_Validator_StringLength.html with the allowEmpty parameter. Thanks a lot !!!!! – John Sep 04 '15 at 13:15
  • OK nice :). But i'm not using the max parameter. Just the min. – John Sep 04 '15 at 19:18
  • @John have you tested if does allow 3 char length passwords? From my understanding you don't want that right?! I believe the default `min` is 0 – cvsguimaraes Sep 04 '15 at 19:23