Functions to validate e-mail, name and phone number

MitkOK 0 Tallied Votes 195 Views Share

Here are two simple functions to validate name and e-mail .

int valName( string $arg1 )

- this function returns 1 if name is correct, 0 if incorrect

int valMail( string $arg1 )

- this function returns 1 if name is correct, 0 if incorrect

// valName()

function valName($name) 

{
      $name = preg_replace(‘/[\s]+/is’, ‘ ‘, $name);
      $name = trim($name);

      return preg_match(‘/^[a-z\s]+$/i’, $name);            
}


// valMail()

function valMail($email)
{ 

 $regexp='/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/';
 
 return preg_match($regexp, trim($email));

}

Dani AI

Generated

Good starting point, — two quick cautions before improvements: the code you pasted shows mangled quotes (copy/encoding issue) which will break PHP, and the name/email regexes are overly strict (ASCII-only names; fragile email regex). preg_match returns 1, 0 or false on error, so cast to (bool) if you want true/false results and prefer built-in validators where possible.

A safer, more international name check (collapse extra spaces, allow letters from any script plus common connectors):

function validate_name($name) {
    $name = preg_replace('/\s+/u', ' ', trim($name));
    return (bool) preg_match('/^[\p{L}\p{M}\'\-\s]{2,100}$/u', $name);
}

For e-mail, prefer PHP's filter and then (optionally) check DNS for MX/A records — regexes trying to implement RFC 5322 are brittle; delivery is a separate concern (only a verification email proves deliverability):

function validate_email($email) {
    $email = trim($email);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
    $domain = substr(strrchr($email, "@"), 1);
    return checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A');
}

Phone numbers are best handled with a library (Google's libphonenumber) for parsing/formatting/validation. If you only need a simple E.164 sanity check, normalize then validate like this:

function validate_phone_e164($number) {
    $n = preg_replace('/[^\d\+]/', '', $number);
    return (bool) preg_match('/^\+?[1-9]\d{1,14}$/', $n);
}

Final notes: validate on the server (client-side is UX only), separate validation from sanitization/encoding, and prefer sending a confirmation message for critical checks (email/phone) rather than relying solely on regex or DNS lookups.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.