表单多行从表提交时的验证问题!
使用laravel 5.8 做后台管理,表单验证时采用注入FormRequest的方式;
在定义rule的时候,对数组型字段的验证,定义时会有带条件验证;
public function rules()
{
return [
'cInvCode.'=>[
'required',
'exists:fb_inv,cInvCode',
],
'cInvName.'=>[
'exists:fb_inv,cInvName,cInvCode,'.$this->cInvCode[0],
],
];
}
目前的问题是,对于从表商品行,商品编码cInvCode和商品名称cInvName, 关联到商品档案表fb_inv
cInvName. 会自动匹配表格行,可后面条件验证时需要取同表行的商品编码cInvCode内容,
使用$this->cInvCode,或者$this->cInvCode[],都无法执行;验证时无法取到同一行的cInvCode
代码中$this->cInvCode[0]是临时使用,实际上不可能都按第一行商品编码来条件验证,肯定是单行内的字段匹配性验证;可如何写这个表格自动按行取值的表达式,文档中没有找到合适的答案,百度也没有结果,不知道各位有没有遇到过这种情况,如何在验证cInvName.*时定义按行取cInvCode进行条件验证的表达式;希望大家不吝指教!
大神们都不太有时间解决这个问题,我只能自己折腾;
'cInvName.*'=>[
'exists:fb_inv,cInvName,cInvCode,'.implode('|',$this->cInvCode),
],
E:\laravel-5.8.3\vendor\laravel\framework\src\Illuminate\Validation\ValidationRuleParser.php
修改源代码,增加内容解析处理并替换rule内容
protected function explodeWildcardRules($results, $attribute, $rules)
{
$pattern = str_replace('*', '[^.]*', preg_quote($attribute));
$data = ValidationData::initializeAndGatherData($attribute, $this->data);
foreach ($data as $key => $value) {
if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\z/', $key)) {
foreach ((array) $rules as &$rule) {
$this->implicitAttributes[$attribute][] = $key;
//以下代码处理从表的条件定位取值
//检查条件验证值是否为数组转换的多值串
//如果是的话,按前面的属性值下标进行定位取值
[$rule_attrname, $rule_subscript] = explode('.', $key, 2);
foreach ((array) $rule as $detail=>&$rule_Detail) { //多规则遍历
//存在数组转换的多值串的情况下进行下标定位拆解取值并替换
if (Str::contains($rule_Detail, '|')) {
if (strpos($rule_Detail, ':') !== false) {
[$rule_key, $rule_para] = explode(':', $rule_Detail, 2);
$rule_paralist = explode(',', $rule_para);
foreach($rule_paralist as $part=>$rule_part) { //各参数遍历
if (Str::contains($rule_part, '|')) {
$rule_getvalue = explode('|', $rule_part);
//将数组内容替换成指定从表行匹配的值
$rule[$detail] = Str::replaceFirst($rule_part, $rule_getvalue[$rule_subscript], $rule_Detail);
break;
}
}
}
}
}
//以上代码处理从表的条件定位取值
$results = $this->mergeRules($results, $key, $rule);
}
}
}
return $results;
}
目前来说,解决了当前问题!后面还有新的需求需要解决!比如从表行仓库编码+商品编码匹配库存量,校验从表录入的数量的合法范围!