2014-01-16 19 views
1

我有一個PHP腳本,用於驗證表單。目前它只允許數字/數字。我試圖用幾種方法修改它,但它要麼出錯或得到500錯誤。我只想添加$和。在提交中。修改PHP驗證腳本以允許使用現金標誌和小數

這裏是工作的腳本,僅驗證號碼:

class Quform_Filter_Digits implements Quform_Filter_Interface 
{ 
    /** 
    * Whether to allow white space characters; off by default 
    * @var boolean 
    */ 
    protected $_allowWhiteSpace = false; 

    /** 
    * Class constructor 
    * 
    * @param array $options 
    */ 
    public function __construct($options = null) 
    { 
     if (is_array($options)) { 
      if (array_key_exists('allowWhiteSpace', $options)) { 
       $this->setAllowWhiteSpace($options['allowWhiteSpace']); 
      } 
     } 
    } 

    /** 
    * Filter everything from the given value except digits 
    * 
    * @param string $value The value to filter 
    * @return string The filtered value 
    */ 
    public function filter($value) 
    { 
     $whiteSpace = $this->_allowWhiteSpace ? '\s' : ''; 

     $pattern = '/[^0-9' . $whiteSpace .']/'; 

     return preg_replace($pattern, '', (string) $value); 
    } 

    /** 
    * Whether or not to allow white space 
    * 
    * @param boolean $flag 
    * @return Quform_Filter_Digits 
    */ 
    public function setAllowWhiteSpace($flag) 
    { 
     $this->_allowWhiteSpace = (bool) $flag; 
     return $this; 
    } 

    /** 
    * Is white space allowed? 
    * 
    * @return boolean 
    */ 
    public function getAllowWhiteSpace() 
    { 
     return $this->_allowWhiteSpace; 
    } 
} 
+0

@ jeroen我只是想讓該領域能夠驗證金錢。允許$​​ 00.00 –

+0

@jeroen對不起,他們在我提交時出於維護原因而關閉了,當他們回來時輸入消失了,我很快開始複製錯誤的文件。然後當我幾分鐘前點擊問題時,他們以某種方式得到了正確的草稿。但我只是更新了 –

回答

1

您可以修改你的正則表達式模式,以允許更多的字符:

$pattern = '/[^0-9.$' . $whiteSpace .']/'; 

但是,這也不能保證正確的順序,如例如12$.17會通過。另一種方法是分別檢查的第一個字符,因爲這是唯一一個可能是一個$跡象,你將不得不決定是否可能是一個.

如果你決定要分別檢查的第一個字符,你可以簡單地在其餘部分上使用類似filter_var($value, FILTER_VALIDATE_FLOAT);的東西(或者如果它不是美元符號,則包括第一個字符)。請參閱filter_var()上的手冊。

+0

哦,我認爲它們之間必須有單引號!謝謝 –

+0

要按照正確的順序調整它有多困難? –

+0

我只是檢查第一個字符,如果它是'$',請在其餘部分使用'filter_var',如果不是,則在整個字符串中使用它。這將完全取代你的正則表達式。 – jeroen

相關問題