【发布时间】:2010-06-11 01:29:21
【问题描述】:
如何在 codeiginiter 中使用正则表达式验证表单。我想检查输入:
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
我假设最好的方法是某种回调。我在网上尝试了很多想法,但我似乎无法得到任何工作。
【问题讨论】:
标签: php regex codeigniter
如何在 codeiginiter 中使用正则表达式验证表单。我想检查输入:
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
我假设最好的方法是某种回调。我在网上尝试了很多想法,但我似乎无法得到任何工作。
【问题讨论】:
标签: php regex codeigniter
旧帖但可以直接在输入验证规则中添加正则表达式
$this->form_validation->set_rules()
添加到上面的函数:regex_match[your regex]
【讨论】:
你可以像这样创建一个函数:
function validateRegex($input)
{
if (preg_match('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $input))
{
return true; // it matched, return true or false if you want opposite
}
else
{
return false;
}
}
在您的控制器中,您可以像这样使用它:
if ($this->validateRegex($this->input->post('some_data')))
{
// true, proceed with rest of the code.....
}
【讨论】:
使用 AJAX 怎么样?
$("form").submit(function(e) {
e.preventDefault();
$.post("<?php echo base_url(); ?>regex_check", { username: $("#username").val() }, function (data) {
alert(data);
});
regex_check 函数会包含一个典型的正则表达式检查,例如
function regex_check(){
$this->get->post('username');
if(eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $username)){
return TRUE;}else{return FALSE;}
}
只有在所有数据都经过验证后,您才允许成功提交表单。
这些代码 sn-ps 应该可以帮助您验证数据。
【讨论】:
这是提交给account/signup的完整解决方案
在account 控制器中:
function signup(){
if($_POST){
$this->form_validation->set_rules('full_name', 'Full Name', 'required|min_length[3]|max_length[100]');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|callback_check_password');
if ($this->form_validation->run() == FALSE){
echo validation_errors();
}
else{
// form validates, now can do stuff such as insert into database
// and show the user that they successfully signed up, i.e.,:
// $this->load->view('account/signup_success');
}
}
}
check_password 回调函数也在account 控制器中:
function check_password($p){
$p = $this->input->post('password');
if (preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8}/', $p)) return true;
// it matched, see <ul> below for interpreting this regex
else{
$this->form_validation->set_message('check_password',
'<span class="error">
<ul id="passwordError">
<li> Password must be at least:</li>
<li> 8 characters</li>
<li> 1 upper, 1 lower case letter</li>
<li> 1 number</li>
</ul>
</span>');
return false;
}
}
【讨论】: