1

i want to validate this form with php. I want to use regex, and the strlen() function. this is the Form ===>

<form class="form" action="index.php" method="post" name="form">
<p class="form_field">
    <label>Name :</label> 
    <input class="input" type="text" name="name" placeholder="Name"> 
    * <?php echo  $nameErr; ?><br>
</p>
<p class="form_field">
    <label>Email :</label> 
    <input class="input" type="text" name="email" placeholder="Email"> 
    * <?php echo  $emailErr; ?><br>
</p>
<p class="form_field">
    <label>Gender :</label> 
    <input class="radio" type="radio" name="gender"> male
    <input class="radio" type="radio" name="gender"> female 
    * <?php echo  $genderErr; ?><br>
</p>
<p class="form_field">
    <label>Website :</label>
    <input type="text" name="website" placeholder="Website"> 
    <?php echo $websiteErr; ?> <br>
</p>
<p class="form_field">
    <label>Comment :</label> 
    <textarea rows="5" cols="30" name="comment" placeholder="your comment ..."></textarea> 
    * <?php echo  $commentErr; ?> <br>
</p>
<input class="submit" type="submit" name="submit" placeholder="Submit" >

and this is my php function to validate it ==>

function validate_forms($user_input, string $field){
    $input_length = strlen($user_input);

    if($field = "name"){
        if($input_length > 8){
            $message = "the name should be less than 32 characters";
        } else{
            if( !preg_match("/^[A-Za-z. ]*$/", $user_input) ){
                $message = "Only letters and white space are allowed ";
            } else {
                $get_input = $user_input;
            }
        }

    } elseif ($field = "URL") {
        if(!preg_match("/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/", $_POST['website'])){
            $message = "Please enter a valid url ";
           } else {
            $get_input = $user_input;
           }

    } elseif ($field = "email") {
        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
           } else {
            $get_input = $user_input;
           }
    }
    return $message;}

What i want to accomplish is to make my function return the $message variable if no condition is met, and get and return the $user_input if all conditions are met.

i think it is possible to return an array but i don't know how.

Also i think i'm not respecting the best practices here so it will be so nice of you to help understand the best way to validate my form(a more faster and secure way)

this is for learning purposes , so any more informations or books, tutorials and courses recommendations are welcomed.Thank you in advance

PS: I know an Object Oriented approach will be better in this case, but i want to learn the procedural way first.

4
  • 1
    many people have names that would fail your chcek Commented Sep 14, 2017 at 21:39
  • 1
    both the length and character restrictions are unrealistic. kalzumeus.com/2010/06/17/… Commented Sep 14, 2017 at 21:50
  • 1
    comparison operators need to be double equal signs '==' Commented Sep 14, 2017 at 21:54
  • @rtfm thank you, this is a very helpful article, i knew that 8 characters for a name is unrealistic but i didn't know that my regular expression is too. well what lenght and character restrictions do you recommend? thank you so much. Commented Sep 14, 2017 at 22:33

3 Answers 3

2

You should use preg_match only to validate names, for other fields (email & url) there is already a way to test them using php filters

define( 'NAME_MIN_LENGTH', 8 );
define( 'NAME_MAX_LENGTH', 32 );

function validate_form( $user_input = null, $field = null , &$error_message )
{
    $error_message = '';

    switch ( $field ) {

        case 'name':

            $name_len = strlen( $user_input );

            if( $name_len < NAME_MIN_LENGTH ){

                $error_message = 'Name too short, minimin is '. NAME_MIN_LENGTH .' caracters';
                return false;
            }

            if( $name_len > NAME_MAX_LENGTH ){

                $error_message = 'Name too long, maximum is '. NAME_MAX_LENGTH .' caracters';
                return false;
            }

            if( ! preg_match( '/^[a-zA-Z][a-zA-Z\. ]+[a-zA-Z]$/' , $user_input ) ){

                $error_message = 'Invalid name';
                return false;
            }
            break;

        case 'url':

            if( ! filter_var( $user_input, FILTER_VALIDATE_URL ) ){

                $error_message = 'Invalid URL';
                return false;
            }
            break;

        case 'email':

            if( ! filter_var( $user_input, FILTER_VALIDATE_EMAIL ) ){

                $error_message = 'Invalid Email';
                return false;
            }
            break;

        default:

            $error_message = 'Invalid field';
            return false;
            break;
    }

    return $user_input;
}

// TESTS


$valid_name = 'John Doe';
$invalid_name_1 = 'Foo';
$invalid_name_2 = 'Foooooooooooooooooooooooooooooooo';
$invalid_name_3 = 'Foo#$*=+-!:;,,';

$valid_email = '[email protected]';
$invalid_email = 'foo.bar@';

$valid_url = 'http://www.example.com/';
$invlide_url = 'foo-bar';

$test_values = [ 
                    $valid_name=>'name',
                    $invalid_name_1=>'name',
                    $invalid_name_2=>'name',
                    $invalid_name_2=>'name',

                    $valid_email=>'email',
                    $invalid_email=>'email',

                    $valid_url=>'url',
                    $invlide_url=>'url'
                ];

$error_message = '';
echo '<pre>';
foreach( $test_values as $value => $field  ){

    if( ($valide_value = validate_form( $value, $field, $error_message )) === false ){

        printf( "%33s :   Is not a valid %s (%s)%s", $value, $field, $error_message, PHP_EOL );
    }else{

        printf( "%33s :   Is a valid %s%s", $valide_value, $field, PHP_EOL  );
    }
}
echo '</pre>';

The above example gives the following output

                             John Doe :   Is a valid name
                                  Foo :   Is not a valid name (Name too short, minimin is 8 caracters)
    Foooooooooooooooooooooooooooooooo :   Is not a valid name (Name too long, maximum is 32 caracters)
                 [email protected] :   Is a valid email
                             foo.bar@ :   Is not a valid email (Invalid Email)
              http://www.example.com/ :   Is a valid url
                              foo-bar :   Is not a valid url (Invalid URL)
Sign up to request clarification or add additional context in comments.

4 Comments

ooh thank you man your piece of code is awesome . One thing, if i want to get the user input and store it in a variable if all the conditions are met and the $error_message is empty, should i do this ? ==> if( !empty( $error_message ) ){ return $error_message; }else { $input = $user_input ; return $input; } and if you can explain this characters (%33s : Is not a valid %s (%s)%s) and (PHP_EOL) it will be so nice. thank you so much
You are welcome, I just did an update to the code, see the TEST section to understand how to use this function.
PHP_EOL for adding a new line.
This is the only way to handle errors in this case, else you should use Exceptions.
1

First, I would recommend you look at parsleyjs, it is a great library for form check on the frontend; this allows for you to create the conditions before sending the data to the server to check it. It is more practical, and simpler to use. If you are interested, the link http://parsleyjs.org

You should create an array, and pass back to the user in that way. It will allow you to check for an error, or success.

For example:

// note the "==" to check value
// single equal sign assigns value
if($field == "name"){
    if($input_length > 8){
        $response = array(
            'is_error' => true,
            'message' => "the name should be less than 32 characters"
        );
    } else{
        if( !preg_match("/^[A-Za-z. ]*$/", $user_input) ){
            $response = array(
                'is_error' => true,
                'message' => "Only letters and white space are allowed "
            );
        } else {
            $get_inputp['name'] = $user_input;
            $response = array(
                'is_error' => false,
                'message' => $user_input
            );
        }
    }
}

//... more code here ...//

// now return the response
return $response;

Then you can check for a message on the user end like this:

$submit = validate_form('', '');

if ($submit['is_error'] === true)
{
    echo $submit['message']; // and do whatever you need to in error case
}

This simplifies having to try and return two values, you only return the array containing a boolean error for error check, and then a message, you can also add more information on that array.

For your checking of values, specifically for your URL use the same method you used for emails. filter_var allows for you to check the URL:

$valid_url = filter_var($_POST['website'], FILTER_VALIDATE_URL);

3 Comments

This isn't very DRY, as you are rebuilding the $response array in each block.
@Samuel thank you for you great response. this exactly what i wanted to do. just one thing, i think now i don't need to put this line " $get_inputp['name'] = $user_input; " because it do nothing am i mistaken?. thank you for url validation advise and for the js library, i will check it out. thank you a second time :)
No problem man, glad I could help! Yes I don't think it would need it.
0

I would recommend converting this to a case statement and store the errors in an associative array by field name as follows:

$errors = [];

switch($field){
    case 'name':
        if($input_length > 32){
            $errors[$field] = "the name should be less than 32 characters";
        } 
        break;
    case 'url':
        ...
        break;
    case 'email':
        ...
        break;
}    

Then test the error array

if(!empty($errors)){
    print_r($errors);
}

1 Comment

thank you for your response, i did think of doing it it this way, but the problem is: how should i get the user-input if all the conditions are met.this is the problem i want to return an error message and display it in front of the form fields if there is a character or length error. but i there are no errors i want to get the user input and store it in a variable so i can store it in a database or work with it later .

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.