如何防止代码点火器3.1.11中的可选字段被验证



我正在进行一个使用CodeIgniter 3.1.11版本的项目。

目前,我正在处理一个表单,需要验证表单中的所有字段,只有一个字段是可选的。我看到CodeIgniter3每次提交表单时都会验证所有字段。下面是我表单的代码。

<form action="/save_shipping_profile" method="POST" id="shipping_profile">
<table cellPadding="15" width="100%">


<tr>
<td width="150">Address:</td>
<td>
<input id="address" class="experian_address_autocomplete" type="text" name="address1" 
value="<?= $shippingInfo['shipping_address']; ?>" size="50" required /> 
<span class="required">*</span>
</td>
</tr>
<tr>
<td width="150">Address 2<br /><span style="color:#a6a6a6;font-size:10px;">(Apt, Suite #, etc..)</span></td>
<td><input id="address2" type="text" name="address2" value="<?= $shippingInfo['shipping_address2']; ?>" size="50" autocomplete="address-line2" /></td>
</tr>
<tr>
<td width="150">City:</td>
<td><input id="city" type="text" name="city" value="<?= $shippingInfo['shipping_city']; ?>" size="50" required autocomplete="address-level2" /> <span class="required">*</span></td>
</tr>
<tr>
<td width="150">State / Province:</td>
<td>
<input id="state" type="text" name="state" value="<?= $shippingInfo['shipping_state']; ?>" size="50" />";
</td>
</tr>
<tr>
<td width="150">Zip / Post Code:</td>
<td><input id='zip' type="text" name="zip" value="<?= $shippingInfo['shipping_zip']; ?>" size="15" required autocomplete="postal-code" /> <span class="required">*</span></td>
</tr>

**<?php if ($site_options['show_phone_number_shipping_profile']): ?>
<tr>
<td width="150">Phone Number:</td>
<td><input id='phone' type="tel" name="phone" value="<?= $shippingInfo['billing_phone']; ?>" size="15" autocomplete="phone-number" /></td>
</tr>
<?php endif; ?>**

<tr>
<td width="150">&nbsp;</td>
<td><input id="save_shipping" type="submit" name="submit" value="Save Shipping Information" /></td>
</tr>
</table>
</form>

下面是我的控制器文件

function save_shipping_profile()
{
$this->load->library('form_validation');

$this->form_validation->set_message('address_check', 'The %s field may not be an address.');
$this->form_validation->set_rules('address1', 'Address', 'required|trim|xss_clean|callback_address_check');
// $this->form_validation->set_rules('phone', 'Phone', 'permit_empty');

if(!$this->form_validation->run())
{
$array = array();
$array['error'] = '1';
$array['message'] = validation_errors("- "," ");

}
else
{
// Execute the main code

}
}

我试图跳过电话字段的验证。我在研究中发现,在CodeIgniter 4中,下一行将使电话字段成为可选字段,但它对CodeIgniter3.1.11不起作用。我研究了各种各样的文章,但没有找到任何相关的答案。有人能给我推荐一下吗?

$this->form_validation->set_rules('phone','phone','permit_empty'(;

有人能帮我吗?

要获得更多控制,请不要使用->set_rules('field', 'label', 'rules')。使用阵列:

$config = [
[
'field' => '',
'label' => '',
'rules' => '',
],
...
];
$this->form_validation->set_rules($config);

所以定义您的通用数组,当您使用phone时,只需将其添加到数组中即可。

最新更新