0

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.';
}}
1
  • Validate functions should ONLY return BOOLEAN values. You are on the wrong track. This should be similar to this if ( ! is_zip_valid($zip) ){ /* add error message to container */ } Commented Apr 19, 2013 at 3:10

2 Answers 2

1

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)) ...
Sign up to request clarification or add additional context in comments.

1 Comment

if you talk about foreign chars, then mb_strlen($string, 'UTF-8') would make more sense.
0

For any Unicode (international) letters

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.