Search code examples
phpstringformsvalidationrequiredfieldvalidator

PHP Name Required for Form


I am new to PHP and am trying to get this form to require certain fields to be filled in before allowing a submission. My email, phone number & zip all work, however my Name & does not. It took me a minute to realize why but now I do not know how to work around it.

On my field form I have Name inside the input box for the user to know what to put in that box, my PHP code only checks to see if there is anything A-z and a space possibly. Is there any way to check if it's not just "Name" in the field??? Thanks & hope that makes sense! :)

PHP CODE

$string_exp = '/^[a-zA-Z0-9 ]*$/';
if(!preg_match($string_exp,$name)) {
$error_message .= 'The Name you entered does not appear to be valid.<br />';
}

HTML CODE

<label for="name"></label><input type="text" class="rounded" name="name" size="26"
value="Name" style="color:#775594;" onblur="if(this.value==''){this.value='Name'}"
onFocus="if(this.value=='Name'){this.value=''}" />

Solution

  • Add another condition:

    $string_exp = '/^[a-zA-Z0-9 ]*$/';
    if(!preg_match($string_exp,$name) || $name == 'Name') {
        $error_message .= 'The Name you entered does not appear to be valid.<br />';
    }
    
    // for any unicode name, accent, umlauts .. etc:
    $string_exp = '/^((\p{L}\p{M}*)|(\p{Cc})|(\p{P}\p{P}\p{N}.{3})|(\p{N})|(\p{Zs}))+$/ui';
    

    Read more about unicode regular expressions.