采用框架:codeIgniter
前端:Vue js
因使用 Vue js 与 element ui 实现前端,使用 Vue resource 来完全所有的请求,所以 codeIgniter 自带的 Form Validation 类无使用。
想着,自己单独去写一个 validator 浪费太多时间,决定使用第三方库 ** symfony/validator **。
Step #1 通过 Composer 安装 symfony/validator
composer require symfony/validator
Step #2 加载绝对路径中的 autoload.php,代码如下:
require_once APPPATH.'third_party/symfony/vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class User extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url_helper');
$this->load->model('User_Model');
}
public function index()
{
$validator = Validation::createValidator();
$violations = $validator->validate('Bernhard', array(
new Length(array('min' => 10)),
new NotBlank(),
));
if (0 !== count($violations)) {
// there are errors, now you can show them
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
}
Step #3 访问 http://www.ci.dev/user/index,输出结果如下:
This value is too short. It should have 10 characters or more.