user2168066
user2168066

Reputation: 635

Validation function for numeric field

I am finishing up this website and working on the last couple validations. How can I make the validation for a name field only accept letters and not numbers. And how can i validate a zip code field to contain exactly 5 digits. Below is what I have so far.

//First Name
function check_fname($fname){
if($fname==''){
    return 'Please Enter your First Name.';
}}

//Zip Code
function check_zip($zip){
if(! is_numeric($zip)){
    return 'Please Enter your Zip.';
}}

Upvotes: 0

Views: 74

Answers (2)

VolCh
VolCh

Reputation: 369

For any Unicode (international) letters

if (preg_match('/^\pL+$/u', $fname)) ...

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

Regular expressions:

if (preg_match('/^[a-z]+$/i', $fname)) ... // At least one letter

if (preg_match('/^\d{5}$/', $zip)) ... // 5 digits

For the name, depending on your demographic you might want to allow foreign characters I recommend this solution which is more forgiving:

if (strlen($fname) > 0 && ! preg_match('/\d/', $fname)) ...

Upvotes: 1

Related Questions