User input validation, client-side or server-side? [PHP/JS]

后端 未结 6 677
失恋的感觉
失恋的感觉 2020-12-10 08:08

Is it better to validate user input before it\'s sent to the server with JS or server side with PHP? Or maybe it\'s worth doing both just to be on the safe side?

I\'

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 08:40

    You should validate this on server-side. The client-side validation is optional. You can declare types of validation for fields, and build generic validator for your forms. If you don't know what i mean try looking at AngularJs declarative code building. It's the best way to build forms, also Angular is good and very fast framework for building forms.

    http://angularjs.org/

    http://docs.angularjs.org/#!/cookbook/advancedform

    Look at this lines:

     
    ,

    For your server side you can also define some structure, which will contain form fields, validation methods, and error string for each field. Then in loop, validate each field based on your information structure. You can easily manage forms builded that way.

    Example in PHP:

    Form data:

    $formData = array (
        array(
         'ID' => "name",
         'validate' => '/.+/',
         'label' => 'Your name',
         'errorMsg' => "This field is required",
         'type' => 'text' 
        ),
     array(
             'ID' => "Phone number",
             'validate' => '/^[0-9+ ]+$/',
             'label' => 'Numer telefonu',
             'errorMsg' => "Please provide proper telephone number",
             'type' => 'text'
            )
    );
    

    Validator and form generator (sorry for simple and messy code here):

    $s = '';
    foreach ($formData as $input){
        $s .= sprintf('',$input['ID'],$input['label']);
        if (isset($_POST[$input['ID']]) && !empty($input['validate']) && !preg_match($input['validate'],$_POST[$input['ID']])){
            $error = true;
             $s .= sprintf('
    %s
    ',$input['errorMsg']); } if (isset($_POST[$input['ID']])) $htmlMsg = str_replace('%'.$input['ID'].'%',$_POST[$input['ID']],$htmlMsg); if ($input['type'] == 'textarea'){ $s .= sprintf('',$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:'')); } else { $s .= sprintf('',$input['type'],$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:'')); }

    }

提交回复
热议问题