0

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.

George0541
  • 43
  • 1
  • 8

2 Answers2

0

You should be ok with URL safe regex ^[a-zA-Z0-9_-]*$

const regex = new RegExp('^[a-zA-Z0-9_-]*$');
const shouldBeValid = ['domain-name', 'domainname', 'domain'];
const shouldBeInvalid = ['domain-name.com', 'domainname.cz', 'domain.co.uk'];
shouldBeValid.forEach(item=>console.log(item, 'is', regex.test(item)));
shouldBeInvalid.forEach(item=>console.log(item, 'is', regex.test(item)));

It's javascript snippet just to be able to run it here on the page.

Jax-p
  • 7,225
  • 4
  • 28
  • 58
  • Thank you for your answer. Unfortunately that part allowed for hyphens at the beginning and at the end, so I had to edit it out a bit: ```$pattern = "(\A[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])+\z)";``` – George0541 Aug 02 '21 at 09:18
0

The answer to the problem is changing the pattern to:

$pattern = "(\A[a-zA-Z0-9](?:[a-zA-Z0-9\d-]*[a-zA-Z0-9])+\z)";

Which doesn't allow hyphens at the beginning or the end of the domain, doesn't allow any TLDs, and any other special characters.

George0541
  • 43
  • 1
  • 8