2017-07-17 52 views
0

所以我有這個輸入形式PHP驗證有點兒工作,但

<input type="text" name="squareFoot" value="<?PHP if(isset($_POST['squareFoot'])) echo $squareFoot ?>"><span class="error_message"><?PHP echo " " . $squareFootError; ?></span> 

這是我的驗證(這是肯定的上述表單)

if(isset($_POST['submit'])){ 

     $isSubmitted = true; 

     $squareFoot = $_POST['squareFoot']; 
     $squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); 
     $squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND); 
     $squareFoot = filter_var($squareFoot, FILTER_SANITIZE_SPECIAL_CHARS); 

     if(!is_numeric($squareFoot)){ 
      $isValid = false; 
      $squareFootError = "Please enter a numeric value"; 
     } 

     else if(empty($squareFoot)){ 
      $isValid = false; 
      $squareFootError = "Please enter a numeric value"; 
     } 

     else if($squareFoot < 200){ 
      $isValid = false; 
      $squareFootError = "Please enter a number between 200 and 500,000"; 
     } 

     else if($squareFoot > 500000){ 
      $isValid = false; 
      $squareFootError = "Please enter a number between 200 and 500,000"; 
     } 

     else{ 
/// do math (code not shown) 


// Format Square Footage 
      $squareFootFormat = number_format($squareFoot, 0, '', ','); 

// Display to user 
<p>1. Square Footage being stripped <span class="right_al"><?PHP echo $squareFootFormat; ?></span></p> 

所以我把它設置,使用戶不能輸入html或腳本,用戶必須輸入一個必須在兩個數字之間的數字,並且該數字可以有一個逗號。

我也希望用戶能夠放入類似500.5的東西,但是當測試500.5變成5,005時。

是否因爲 $ squareFootFormat = number_format($ squareFoot,0,'',',');

還是有其他問題嗎? 我有點想把number_format()放在裏面,因爲如果它的數字很大,比如100,000,這個數字就更容易閱讀。我可以這樣做嗎? 感謝您的幫助。

+1

'$ squareFoot = filter_var($ squareFoot,FILTER_SANITIZE_SPECIAL_CHARS);''將刪除任何'.',其中浮點值將是。 –

+1

選中此項:https://3v4l.org/663OQ以更好地理解您的代碼。基本上filter_var將你的500.5轉換成5005.問題是你期望在最後得到什麼? 500? 501? – Edwin

+0

我要去500.5,但我想我可以住在舍入。 – theBartender

回答

1

您的filter_var不會允許500.5作爲值。

$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);

+0

謝謝。這工作。任何想法爲什麼W3學校說... FILTER_FLAG_ALLOW_THOUSAND - 允許千分隔符(如,) https://www.w3schools.com/php/filter_sanitize_number_float.asp – theBartender

1

大約只有這樣做什麼:

<?php 


$squareFoot = $_POST['squareFoot']; 
$smallest = 1; 
$greatest = 100000; 
    if(is_numeric($squareFoot)) { 
     if($squareFoot < $greatest && $squareFoot > $smallest) { 
      //do what you want 
      echo number_format($squareFoot, 1, '.', ','); 
     } 
     else { 
      echo "Please enter a number between " .$smallest . " and ".$greatest; 
     } 
    } 
    else { 
     echo "Please enter a numeric value"; 
    } 
?> 

看起來simplier給我。

+0

感謝您的回答。不是我在找的東西,但很簡單。 – theBartender