【发布时间】:2019-03-29 14:59:22
【问题描述】:
简介:
我已验证空字符串的请求值。
代码:
if(isset($request->name)) {
$this->validate($request, [
'name' => [
function ($attribute, $value, $fail) {
if (mb_strlen(preg_replace('/\s/', '', $value)) == 0) {
$fail($attribute.' is can't be empty.');
}
}
]
]);
$user->name = $request->name;
$user->save();
}
也厌倦了自定义规则。
规则代码:
public function passes($attribute, $value)
{
$result = preg_replace('/\s/', '', $value);
return mb_strlen($result) == 0 ? false : true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return "Attribute value can't be empty string.";
}
规则测试代码:
if(isset($request->name)) {
$this->validate($request, [
'name' => [
new IsEmptyString
]
]);
$user->name= $request->name;
$user->save();
}
问题:
哪里有错误?当我检查空字符串的请求值时,为什么 laravel 不发送验证错误消息?
谢谢!
【问题讨论】:
-
当然验证不适用于空字符串。验证甚至不需要空字符串,因为您已将其放在
if条件中。 -
@Tharaka Dilshan 很好理解,但是如果我只用条件单独检查每个字段呢?那怎么做验证呢?在我的情况下,数据库中也没有记录空字符串,但我无法通知用户他输入了一个空字段。
-
条件中的其他类型的验证在我的情况下有效,只有当空字符串不起作用时。
-
是的,那是因为您已将 validate 函数放在
if(isset($request->name))中。难道你不明白,如果name为空,则验证函数甚至不会被调用。 -
我了解你@Tharaka Dilshan。但是我怎么能告诉用户他输入了一个空字符串呢?
标签: laravel validation laravel-5.7