PHP를 사용한 간단한 동적 양식 유효성 검사 기능
                                            
                                                
                                                
                                                
                                                
                                                
                                                 27320 단어  phpjavascripthtmlmysql
                    
이 튜토리얼에서는 Laravel 유효성 검사와 동일한 구문을 가진 PHP를 사용하여 간단한 동적 양식 유효성 검사 함수를 코딩합니다. 유효성 검사는 데이터베이스에 저장하기 전에 가장 중요한 것 중 하나라는 것을 알고 있습니다. 예를 들어 컬럼의 크기가 100자까지만 허용되는데 최대 글자 수를 확인하지 않고 사용자가 100자를 넘게 입력하면 저장된 데이터가 잘립니다.
이 기능의 기본 기능은 다음과 같습니다.
이 기능을 사용하는 방법?
이 기능을 사용하는 방법에 대한 아래 코드를 확인하십시오.
// Validate the data
$validation = validate($_REQUEST, [
    'email' => 'required|email|unique:employees|min:2|max:100',
    'first_name' => 'required|min:2|max:100',
    'last_name' => 'required|min:2|max:100',
    'address' => 'required|min:2|max:250'
]);
위에서 볼 수 있듯이 다음과 같은 매개변수를 사용하여 validate() 함수를 호출합니다.
function validate($input, $rules) {}
$input - 배열 타입으로 $_REQUEST, $_POST Super Global 변수에 적합합니다. 다음은 배열의 샘플 형식입니다.
Array
(
    [email] => email@gmail.com
    [first_name] => Ronard
    [last_name] => Cauba
    [address] => Dumaguete City, Negros Oriental, Philippines
)
$rules - 필드 유효성 검사 값이 있는 배열 유형입니다. 아래는 샘플 배열 값입니다.
[
    'email' => 'required|email|unique:employees|min:2|max:100',
    'first_name' => 'required|min:2|max:100',
    'last_name' => 'required|min:2|max:100',
    'address' => 'required|min:2|max:250'
]
유효성 검사 구문
$input 매개변수의 필드 이름인 배열 키 이름과 $rules 매개변수의 배열 키 이름은 동일해야 합니다. $input 및 $rules 매개변수에 대한 위의 예를 볼 수 있습니다.
필수 구문 - 필드가 필수인 경우 필드 이름과 함께 $rules 매개변수에 "required"를 추가해야 합니다. 예를 들면 다음과 같습니다.
[
..
    'email' => 'required'
..
]
이메일 구문 - 이메일이 유효한지 필드의 유효성을 검사해야 하는 경우 필드 이름과 함께 $rules 매개변수에 "email"을 추가해야 합니다. 예를 들면 다음과 같습니다.
[
..
    'email' => 'required|email'
..
]
참고: 보시다시피 이제 이메일 필드에 대해 필수 및 이메일 유효성 검사가 있습니다. 따라서 구분 기호 "|"가 필요합니다. (바 라인)
고유 구문 - 필드가 테이블에 대해 고유한 값이어야 하는 경우 "unique:{table_name}"을 추가해야 하므로 테이블 이름이 "users"인 경우 다음과 같아야 합니다.
[
..
    'email' => 'unique:users'
..
]
최소 구문 - 필드에 최소 문자 수가 있는 경우 "min:{minimum_number}"를 추가해야 합니다. 아래 샘플 코드는 다음과 같습니다.
[
..
    'email' => 'min:10'
..
]
최대 구문 - 필드에 최대 문자 수가 있는 경우 "max:{maximum_number}"를 추가해야 합니다. 아래 샘플 코드는 다음과 같습니다.
[
..
    'email' => 'max:100'
..
]
완벽한 양식 유효성 검사 기능
이제 양식에 대한 기본 유효성 검사가 있습니다. 이제 나는 당신이 사용할 수 있는 완전한 함수 소스 코드를 제공할 것입니다.
첫째,
config.php<?php
    //set the servername
    define("SERVER_NAME", "localhost");
    //set the server username
    define("SERVER_UNAME", "root");
    // set the server password (you must put password here if your using live server)
    define("SERVER_UPASS", "");
    // set the table name
    define("SERVER_DB", "demos");
    // Include functions file
    require_once 'functions.php';
    // Connect to database
    $db = connectDB();
?>
둘째,
functions.php<?php
    function connectDB() 
    {
        $db = new mysqli(SERVER_NAME, SERVER_UNAME, SERVER_UPASS, SERVER_DB);
        if ($db->connect_errno) {
          echo "Failed to connect to MySQL: " . $db->connect_error;
          exit();
        }
        return $db;
    }
    function validate($input, $rules) 
    {
        $errors = [];
        if(is_array($input)):
            foreach($rules as $fieldName=>$value):
                $fieldRules = explode("|", $value);
                foreach($fieldRules as $rule):
                    $ruleValue = _getRuleSuffix($rule);
                    $rule = _removeRuleSuffix($rule);
                    if($rule == "required" && isEmptyFieldRequired($input, $fieldName)):
                        $errors[$fieldName]['required'] = _removeUnderscore(ucfirst($fieldName)) . " field is required.";
                    endif;
                    if($rule == "email" && !isEmailValid($input, $fieldName)):
                        $errors[$fieldName]['email'] = _removeUnderscore(ucfirst($fieldName)) . " field is invalid.";
                    endif;
                    if($rule == "min" && isLessThanMin($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['max'] = _removeUnderscore(ucfirst($fieldName)) . " field is less than " . $ruleValue . " characters of the minimum length.";
                    endif;
                    if($rule == "max" && isMoreThanMax($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['max'] = _removeUnderscore(ucfirst($fieldName)) . " field is more than " . $ruleValue . " characters of the maximum length.";
                    endif;
                    if($rule == "unique" && !isRecordUnique($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['unique'] = _removeUnderscore(ucfirst($fieldName)) . " field is already exists.";
                    endif;
                endforeach;
            endforeach;
        endif;
        return $errors;
    }
    function isEmptyFieldRequired($input, $fieldName) 
    {
        return $input[$fieldName] == "" || empty($input[$fieldName]);
    }
    function isLessThanMin($input, $fieldName, $value) 
    {
        return strlen($input[$fieldName]) < $value; 
    }
    function isMoreThanMax($input, $fieldName, $value) 
    {
        return strlen($input[$fieldName]) > $value;
    }
    function isRecordUnique($input, $fieldName, $value) 
    {   
        // Connect to database
        $db = connectDB();
        // SQL Statement
        $sql = "SELECT * FROM ".$value." WHERE ".$fieldName."='".$input[$fieldName]."'";
        // Process the query
        $results = $db->query($sql);
        // Fetch Associative array
        $row = $results->fetch_assoc();
        // Close db connection
        $db->close();
        // If the result is not array so the record is unique
        return !is_array($row);
    }
    function isEmailValid($input, $fieldName) 
    {
        $email = $input[$fieldName];
        if(!empty($email) || $email != ""):
            return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)) ? FALSE : TRUE;
        else:
            return TRUE;
        endif;
    }
    function _removeUnderscore($string) 
    {
        return str_replace("_", " ", $string);
    }
    function _removeRuleSuffix($string) 
    {
        $arr = explode(":", $string);
        return $arr[0];
    }
    function _getRuleSuffix($string) 
    {
        $arr = explode(":", $string);
        return isset($arr[1])?$arr[1]:null;
    }
?>
셋째, 코드 구현
<?php
    // include config file
    require_once 'config.php';
    // Validate the data
    $validation = validate($_REQUEST, [
        'email' => 'required|email|unique:employees|min:2|max:100',
        'first_name' => 'required|min:2|max:100',
        'last_name' => 'required|min:2|max:100',
        'address' => 'required|min:2|max:250'
    ]);
    // Defined $result as array
    $result = [];
    // Check if no validation errors
    if(!count($validation)):
       //do something here
    else:
       //do something here to display the errors
       $result['has_error'] = 1;
       $result['errors'] = $validation;
    endif;
    // Encode array into json format (this is useful if your using ajax)
    echo json_encode($result);
?>
넷째, 에러가 발생했을 때의 결과.

이상입니다. 이 기본 기능이 양식 유효성 검사를 동적으로 도울 수 있기를 바랍니다. 이 자습서가 도움이 되기를 바랍니다. 이 코드를 다운로드하려면 여기https://codeanddeploy.com/blog/php/simple-dynamic-form-validation-function-using-php를 방문하십시오.
참고: 이 튜토리얼에서는 ajax를 사용하므로 ajax 기능이 아닌 기능에 맞게 코드를 조정하면 됩니다.
읽어 주셔서 감사합니다. 행복한 코딩 :)
Reference
이 문제에 관하여(PHP를 사용한 간단한 동적 양식 유효성 검사 기능), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/codeanddeploy/simple-dynamic-form-validation-function-using-php-3fe2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)