If you wanted to add custom Validations for Contact from 7 fields, here is the code
But the name we use in Wordpress back-end should match with $name in the below code. I added validations for URL, Zip and Phone number
For Custom URL use "url" - [text* url]
For Zip Code use "ZipCode" - [text* ZipCode]
For Phone Number we can use "'PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7'" - [text* PhoneNumber1]
<?php
// URL Validations
function get_valid_url( $url ) {
$reg_cond = "((https?|ftp)\:\/\/)?";
$reg_cond .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$reg_cond .= "(\:[0-9]{2,5})?";
$reg_cond .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
$reg_cond .= "([a-z0-9-.]*)\.([a-z]{2,3})";
$reg_cond .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$reg_cond .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";
return preg_match("/^$reg_cond$/", $url);
}
function contact7_validations($result,$tag) {
$type = $tag['type'];
$name = $tag['name'];
if($type == 'text*' && $_POST[$name] == ''){
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
}
// Custom URL Validation
if($name == 'url') {
$url = $_POST['url'];
if($url != '') {
if(get_valid_url($url)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'URL Entered is invalid.';
}
}
}
// Custom Zip Code Validation
if($name == 'ZipCode') {
$ZipCode = $_POST['ZipCode'];
if($ZipCode != '') {
if(!preg_match('/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/', $ZipCode)) {
if(!preg_match('/^\d{5}(-\d{4})?$/', $ZipCode)) {
$result['valid'] = false;
$result['reason'][$name] = 'Zipcode Entered is Invalid';
}
}
}
}
// Phone Validation
$PhoneNumber = array('PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7');
foreach($PhoneNumber as $phoneValid) {
if($name == $phoneValid) {
$validPhone = $_POST[$phoneValid];
if($validPhone != '') {
if(preg_match('/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/', $validPhone)
|| preg_match('/^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/', $validPhone)
&& strlen($validPhone) > 9
&& strlen($validPhone) < 30
&& (int)($validPhone)) {
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Phone Number Entered is Invalid';
}
}
}
}
return $result;
}
//Filter For Text Field
add_filter('wpcf7_validate_text','contact7_validations', 10, 2);
add_filter('wpcf7_validate_text*', 'contact7_validations', 10, 2);
?>
No comments:
Post a Comment