我在控制器中这样做
$sources = array('' => 'Select Source') + Sources::lists('name', 'id');
其中Source
为模型。
然后在视图中,我这样做:
{{Form::select('source_id', $sources, '', $sources)}}
<span>{{$errors->first('source_id')}}</span>
结果HTML是:
<select ="select="" source"="" dubizzle="Dubizzle" name="source_id">
<option value="" selected="selected">Select Source</option>
<option value="1">Dubizzle</option>
</select>
如您所见,第一个选项Select Source
没有值。因此,当我提交表单而不选择任何源时,并像这样验证输入:
$validation = Validator::make(Input::All(), XMLDocument::$rules);
if($validation->passes()){}else{
return Redirect::back()->withInput()->withErrors($validation);
}
I got error message that source_id
is required.
效果很好
我的问题我使用Google Chrome F12开发工具检查HTML,并为Select Source
选项添加了一个值。然后我提交表单,验证没有捕捉到错误。这是因为source_id
有一个值。
黑客可以很容易地操纵HTML,我的服务器和数据库会崩溃,因为这个source_id
是一个外键,所有的东西都连接到它。
我该怎么做呢?
更新1
验证source_id
的规则是:
'source_id' => 'required|integer',
而不是:
$sources = array('' => 'Select Source') + Sources::lists('name', 'id');
你可以使用:
$sources = array('Select Source') + Sources::lists('name', 'id');
所以第一项是:
<option value="0">Select Source</option>
然后在你的规则中添加not_in:0
,例如:
'source_id' => 'required|integer|not_in:0'
它将工作,因为没有元素/记录在你的数据库将有0
的id。
您需要验证所选的源是否是有效的源。您可能可以使用exists
规则来实现这一点,或者如果这是不可行的,那么只需创建一个自定义规则。我想说exists
规则应该符合这个要求。