Search code examples
phpregexzend-frameworkzend-formzend-validate

How can validate multidates in element with regexp PHP Zend Framework


I have field input with multidatepicker select, multidatepicker enter dates in field like: 2016-10-02, 2016-10-13, 2016-10-25. How can validate all dates or one, maybe I can with array regexp validator if exist?

$element_edit->addValidator ('regex', false, array(
    'pattern'=>'/^\d{4}-\d{2}-\d{2}$/',//for only one
    'messages'=>array(
        'regexNotMatch'=>'Validate error')
    )
);
$form->addElement($element_edit);

Solution

  • I believe you are looking for a way to validate a chunk of comma-separated (with or without whitespace in-between) dates in a specific format.

    You may use

    'pattern'=>'/^(\d{4}-\d{2}-\d{2})(?:,\s*(?1))*$/'
    

    See the regex demo

    Details:

    • ^ - start of string
    • (\d{4}-\d{2}-\d{2}) - your single date string pattern: 4 digits, -, 2 digits, - and 2 digits
    • (?:,\s*(?1))* - zero or more sequences of
      • , - comma
      • \s* - 0+ whitespaces
      • (?1) - the same pattern as in Group 1 (your specific date pattern)
    • $ - end of string (may be replaced with \z to disallow newline symbol at the end)