doumao1887 2017-09-14 21:33
浏览 47
已采纳

php“表单验证”函数返回两个值

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.

  • 写回答

3条回答 默认 最新

  • dongse7261 2017-09-14 22:42
    关注

    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 = 'john.doe@example.com';
    $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)
                     john.doe@example.com :   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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?