如何在codeiginiter中使用正則表達式驗證表單。我想檢查輸入反對:使用正則表達式在codeigniter中驗證表單
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
我假設最好的方式是在某種回調。我在網上嘗試了一些想法,但我似乎無法得到任何工作。
如何在codeiginiter中使用正則表達式驗證表單。我想檢查輸入反對:使用正則表達式在codeigniter中驗證表單
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
我假設最好的方式是在某種回調。我在網上嘗試了一些想法,但我似乎無法得到任何工作。
您可以創建這樣一個功能:
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._-][email protected][a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $username)){
return TRUE;}else{return FALSE;}
}
您將只允許成功提交表單,如果所有的數據進行驗證。
這些代碼片段可以幫助您驗證數據。
老的文章,但你可以在輸入驗證規則直接添加正則表達式
$this->form_validation->set_rules()
添加到上面的函數:regex_match[your regex]
這裏有一個完整的解決方案提交給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;
}
}
感謝有趣的解決方案,雖然不是最以Codeigniter爲中心的 – 2013-01-31 22:11:38