2017-07-17 84 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