2014-03-05 22 views
9

我有兩個文本輸入的形式必須是浮動(具體而言,這些文字輸入是geographic coordinates),看了看documentation,發現規則integernumeric但不是float哪個驗證規則用於Laravel 4的float?

我在考慮使用「數字」,因爲文本輸入被禁用,只有當地圖上的標記被移動時,該值纔會改變。

什麼是驗證浮點數的最佳方法?

回答

9

您可以使用正則表達式規則(regex:pattern)對於這一點,因爲要使用驗證Geographic Coordinates,那麼你應該使用正則表達式規則,因爲一個Geo Coord可能看起來像23.710085, 90.406966,這是座標(LAT長)Dhaka Bangladesh,它也可能包含像-33.805789,151.002060這樣的座標。因此,這裏的語法:

$rules = array('form_field_name' => 'required|regex:pattern'); 

或者,也許只是

$rules = array('form_field_name' => 'regex:pattern'); 

因此,模式應該是這樣的/^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$/。所以,最後,它應該是這個樣子(pattern is copied from internet):

$rules = array('form_field_name' => 'regex:/^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$/'); 

檢查Laravel Validation (regex)

+2

我覺得正則表達式是我會學習,接下來的事情,他們似乎是非常有用的。 – Isaias

+0

@Isaias,是的,它在某些情況下非常有用,並且很高興它對您有所幫助。 –

9

numeric規則可用於此,因爲它使用is_numeric()函數來測試值。雖然,通常你會想要使用is_float()函數的東西,因爲表單輸入的格式或字符串,應該使用is_numeric()。下面是來自PHP doc for is_float報價:

要測試一個變量是一個數字或數字字符串(如表單輸入 ,這始終是一個字符串),必須使用is_numeric()來。

0
Validator::extend('gps', function($attribute, $value, $parameters) { 

     if (preg_match('/^-?\d{1,2}\.\d{6,}\s*,\s*-?\d{1,2}\.\d{6,}$/', $value)) { 
      return true; 
     } else { 
      return false; 
     } 
    }); 
2
 'latitude' => 'regex:/^-?\d{1,2}\.\d{6,}$/', 
     'longitude' => 'regex:/^-?\d{1,2}\.\d{6,}$/',