首先,您错误地使用了same验证器。
same 需要一个表单字段名称
例子:
same:field_name
其中,给定字段必须与正在验证的字段匹配。
您可以注册并使用自定义验证规则
Validator::extend('captcha', function($attribute, $value, $parameters)
{
$captcha = \Session::get('captcha');
return $value == $captcha;
});
所以以后你可以这样做:
//session_start(); - Please no need for this in Laravel
//$getsCapt = $_SESSION["captcha"]; - Also remove this not necessary
$rules = array(
'st' => 'required',
'capt' => 'required|numeric|captcha'
);
注意:
使用Session::put 将某些内容保存到会话中,例如\Session::put('something');
还有Session::get 用于从会话中检索值,例如\Session::get('something');
请避免使用$_SESSION而不是Laravel的做事方式
[已编辑] 在哪里注册自定义验证规则?
基本上有两种方法可以在 Laravel 中注册自定义验证规则。
1.从闭包中解决:
如果您通过关闭解决,您可以将其添加到:app/start/global.php
Validator::extend('captcha', function($attribute, $value, $parameters)
{
$captcha = \Session::get('captcha');
return $value == $captcha;
});
2。从类解决
这是扩展自定义验证规则的最佳和首选方式,因为它更有条理且更易于维护。
i. 创建您自己的验证类,CustomValidator.php,可能在 app/validation 文件夹中
<?php namespace App\Validation;
use Illuminate\Validation\Validator;
use Session;
class CustomValidator extends Validator{
public function validateCaptcha($attribute, $value, $parameters)
{
$captcha = Session::get('captcha');
return $value == $captcha;
}
}
注意:注意方法名称中使用的前缀validate,validateCaptcha
ii.创建一个服务提供者,它将解析app/validation文件夹中的自定义验证器扩展
<?php namespace App\Validation;
use Illuminate\Support\ServiceProvider;
class CustomValidationServiceProvider extends ServiceProvider {
public function register(){}
public function boot()
{
$this->app->validator->resolver(function($translator, $data, $rules, $messages){
return new CustomValidator($translator, $data, $rules, $messages);
});
}
}
iii.然后在app/config/app.phpproviders数组下添加CustomValidationServiceProvider:
'providers' => array(
<!-- ... -->
'App\Validation\CustomValidationServiceProvider'
),
iv.并在app/lang/en/validation.php中添加自定义错误信息
return array(
...
"captcha" => "Invalid :attribute entered.",
...
)