Slug Slugfield Regex with CakePHP Validation

Slug Slugfield Regex with CakePHP Validation

Not a very special post, however i simply wanted to make future reference for myself with my CakePHP custom regex validation for slug fields.

'slug' => array(
'RegEx' => array(
'rule' => array('custom', '/^[a-zA-Z0-9-\s_]+$/i'),
'message' => 'Slugs must only contain letters, numbers, underscores and hyphens "-"'),

Also here is my function to convert my titles to a slug :) Using CakePHP of course!

function slugify($data) {
if(empty($data['slug'])){
$slug = low(Inflector::slug($data['title'], '-'));
} else {
$slug = low(Inflector::slug($data['slug'], '-'));
}
return $slug;
}

Posted by VoiDeT

Categorised under CakePHP
Bookmark the permalink or leave a trackback.

2 Comments

  1. Thank you for this, it’s just what I’m looking for – only it doesn’t work… It is allowing spaces in the slug.

    March 10, 2010 @ 3:00 am
  2. VoiDeT

    Seems as though there is a problem in my regex, just change:

    ‘rule’ => array(‘custom’, ‘/^[a-zA-Z0-9-\s_]+$/i’),

    to:

    ‘rule’ => array(‘custom’, ‘/^[a-zA-Z0-9-_]+$/i’),

    That should make the validation trip :)

    March 10, 2010 @ 9:23 am

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

or