PHP code example of xuchen / form-validation

1. Go to this page and download the library: Download xuchen/form-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xuchen / form-validation example snippets

 javascript
{
    "=5.6.0",
        "ext-mbstring": "*"
    }
}
 php


namespace App;


use Xuchen\FormValidation\Validation;

class MyValidation extends Validation
{
    /**
     * 字段验证规则
     */
    protected function fieldsValidationRules()
    {
        return [
            // 使用内置的方法验证字段
            'real_name' => function() {
                // 返回的数组item为`验证方法` => `验证失败时需要返回的错误信息`
                return ['法验证字段,返回false时表示验证失败
            'type' => function() {
                $type = $this->getFormParam('type', 'link', 'strval');
                if (!in_array($type, ['city', 'academy', 'link'])) {
                    $this->_error_msg = '请检查类型';
                    return false;
                }
            }
        ];
    }
}

 php


namespace App\Http\Controllers;


use App\Http\Controllers\Controller;
use App\MyValidation;
use Illuminate\Http\Request;

class MyController extends Controller
{
    public function testPostRoute(Request $request, MyValidation $validation)
    {
        if (!$validation->setFormParams($request->all())->validateFields()) {
            // 使用Validation::getErrorMsg()获取错误信息
            return ['success' => false, 'error_msg' => $validation->getErrorMsg()];
        } else {
            return ['success' => true, 'error_msg' => ''];
        }
    }
}