I am starting in PHP, and I am writing a short filter for domain names, where the form would only accept a domain name without any other input, like dots, hyphens at the beginning or end, or special characters.
Examples:
Valid
domain-name
domainname
domain
etc.
Invalid
domain-name.com
domainname..com
domainname.de
domain.co.uk
-domainname
My code so far:
add_filter( 'gform_field_validation_6_1', 'custom_validation', 10, 4);
function custom_validation( $result, $value, $form, $field ) {
$pattern = "(.de|.com|.cz)";
//$pattern = "^(?!\-)(?:(?:[a-zA-Z\d][a-zA-Z\d\-]{0,61})?[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$";
if ( preg_match ( $pattern, $value ) ) {
$result['is_valid'] = false;
$result['message'] = 'Please enter only valid domain name';
} else {
$result['is_valid'] = true;
$result['message'] = '';
}
return $result;
}
The commented part in the code:
$pattern = "^(?!-)(?:(?:[a-zA-Z\d][a-zA-Z\d-]{0,61})?[a-zA-Z\d].){1,126}(?!\d+) is what I found somewhere else here on SO, but it validated the domain names with top-level domains, which I do not want.