2010-01-03 56 views
3

我只需要添加一個驗證類,以限制數字條目大於24.Codeigniter驗證 - 如何限制數值?

這可能與CI的默認驗證類或我將不得不編寫自定義驗證類嗎?

+0

只是好奇,爲什麼這是downvoted? – 2010-01-04 03:21:04

回答

5

有一個在Form Validation Rule Reference沒有最大或最小的比較功能,讓你可以write your own validation function

這很簡單。像這樣的東西應該工作:

function maximumCheck($num) 
{ 
    if ($num > 24) 
    { 
     $this->form_validation->set_message(
         'your_number_field', 
         'The %s field must be less than 24' 
        ); 
     return FALSE; 
    } 
    else 
    { 
     return TRUE; 
    } 
} 


$this->form_validation->set_rules(
     'your_number_field', 'Your Number', 'callback_maximumCheck' 
    ); 
3

當然可以,只需製作自己的驗證函數並將其添加爲驗證規則的回調即可。見http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

因此,你將有

... 
$this->form_validation->set_rules('mynumber', 'This field', 'callback_numcheck'); 
.... 
function numcheck($in) { 
    if (intval($in) > 24) { 
    $this->form_validation->set_message('numcheck', 'Larger than 24'); 
    return FALSE; 
    } else { 
    return TRUE; 
    } 
} 
+0

感謝您的回答! – 2010-01-04 03:21:52

6

您可以使用驗證規則 「greater_than[24]

例如像

$this->form_validation->set_rules('your_number_field', 'Your Number', 'numeric|required|greater_than[24]');