Skip to content

Instantly share code, notes, and snippets.

@thetrickster
Last active January 10, 2016 03:09
Show Gist options
  • Save thetrickster/d41dbcdac47fe38feeea to your computer and use it in GitHub Desktop.
Save thetrickster/d41dbcdac47fe38feeea to your computer and use it in GitHub Desktop.
Slug Validation for Contact Form 7
<?php
function cf7_slug_validation($result,$tag) {
$type = $tag['type'];
$name = $tag['name'];
if($type == 'text*' && $_POST[$name] == ''){
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
}
//__________________________________________________________________________________________________
// Validate for a slug-like string. Letters, numbers and dashes only but no
// leading or trailing dashes
$Slugs = array('sluglike', 'sluglike1', 'sluglike2');
foreach($Slugs as $Slug){
if($name == $Slug) {
$slug = $_POST[$Slug];
if($slug != '') {
if (!preg_match('/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/', $slug)) {
$result['valid'] = false;
$result['reason'][$name] = 'Please enter only letters, numbers or dashes';
}
}
}
}
return $result;
}
//add filter for text field validation
add_filter('wpcf7_validate_text','cf7_slug_validation', 10, 2); // text field
add_filter('wpcf7_validate_text*', 'cf7_slug_validation', 10, 2); // Req. text field
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment