2011-05-25 121 views
2

我用笨框架笨表單驗證

$this->form_validation->set_rules('money', 'Money', 'integer|required|xss_clean'); 

它驗證貨幣域作爲一個整數下面的PHP代碼。我如何驗證字段爲整數或十進制數字。

我猜它會像

$this->form_validation->set_rules('money', 'Money', '(decimal||integer)|required|xss_clean'); 

簡單的東西,但它不工作!

+0

永遠記住,結合Wesley的說法,您總是可以在設置規則驗證之外添加其他驗證。例如:$陣列=陣列( '金錢'=> filter_var( '$這 - >輸入 - >柱(' 錢'),FILTER_VALIDATE_INT));.這只是一個例子,並不意味着適合您的特殊需求。 – Brad 2011-05-26 22:04:39

回答

7

從CI Form Validation docs

注意:您也可以使用任何PHP函數允許一個參數。

is_numeric()可以爲你工作,但它接受一些非常不同於金錢的格式。

is_float()會工作,除了它會失敗的字符串和整數。

這兩個函數在驗證數字整數或小數時也會過於寬鬆,您通常會將其作爲貨幣值接受。內置的CI decimal()函數需要小數點並允許+-個字符。

是的,我知道 - 沒有幫助,但希望它讓你思考。您想使用的語法根本無法使用。我建議通過擴展Form_validation庫來創建自己的表單驗證規則來驗證金錢。

創建文件/application/libraries/MY_Form_validation.php

事情是這樣的:

class MY_Form_validation extends CI_Form_validation { 

    function is_money($input = '') 
    { 
      // Validate input here and return TRUE or FALSE 
    } 

} 

我最初寫了一個破碎的例子,然後我試着寫東西會工作,並意識到這是給你的。您可能希望允許或不希望允許字符$,,-,+或兩位以上的小數,或者只有一位的小數或逗號分隔數千......使用您認爲合適的驗證方法。

這裏有一個很好的例子,對貨幣格式驗證:How to check if an entered value is currency

+0

@callumander:我添加了一個鏈接,這也將有所幫助。 – 2011-05-25 20:35:17

2

你可以嘗試定製的回調:

$this->form_validation->set_rules('money', 'Money', 'callback_money_type'); 


function money ($param) { 

//conditional statements here 

if(is_int($param) || is_float($param){ 
$this->form_validation->set_message('money_type', 'Your message here'); 
    return false; 

} else { 

    return true; 
} 

} 
0

ctype_digit可能是使用的,它是一個內置的PHP函數。

3

直接使用數字....數字|要求

+1

更適合評論吧? – 2012-10-06 07:35:56

4

這是我在MY_Form_validation類中使用的。

/** 
* Money, decimal or integer 
* 
* @access public 
* @param string 
* @return bool 
*/ 
public function money($str) 
{ 
    //First check if decimal 
    if(!parent::decimal($str)) 
    { 
     //Now check if integer 
     return (bool) parent::integer($str); 
    } 

    return TRUE; 
} 

當然在你/system/language/english/form_validation_lang.php你應該增加相應的消息驗證錯誤和。

0

而不是使用decimal||integer現在我們可以使用numeric來驗證數字字符。

0

您可以使用如下

$這個 - > form_validation-> set_rules( '獎勵', '回報', 'callback_validate_money');

public function validate_money ($input) { 
    if(preg_match('/^[0-9]*\.?[0-9]+$/', $input)){ 
     return true; 
    } else { 
     $this->form_validation->set_message('validate_money','Please enter valid reward!'); 
     return false; 
    } 
}