2013-08-29 76 views
1

我正在收集表單數據,並通過AJAX調用將其發送到PHP驗證腳本。問題是在特殊字符的PHP驗證腳本沒有按預期工作。通過AJAX將特殊字符傳遞給PHP

HTML:

<input type="text" name="firstName" class="firstName" 
     placeholder="[first name]" required autofocus maxlength="25" size="25" /> 

JS:

$(".button").click(function() { 
    var firstName = encodeURIComponent($("input.firstName").val()); 
    var datastring = "firstName=" + firstName; 

    $.ajax({ 
     type: "POST", 
     url: "/scripts/validateSignup.php", 
     data: datastring, 
     cache: false, 
     success: function (errorMessage) { 
      //print to screen 
     } 
    }); 
}); 

PHP驗證

$postData = $_POST; 

if (Filter::validateString($postData['firstName']) == false) { 
    echo "Oops! Some characters used in your first name are not valid."; 
} 

PHP過濾

//Returns true if string is good, false otherwise 
public static function validateString($string) { 
    $string = trim($string); 

    if ($string == null || $string == "") { 
     return false; 
    } else { 
     if (preg_match("/[^\.\,\-\_\'\"\@\?\!\:\;\$\#\%\&\+\= a-zA-Z0-9()]/", $string) == true) { 
      return false; 
     } else { 
      return true; 
     } 
    } 
} 

在一個空字符串它打印錯誤篩選就好了。但是,如果我做了類似「〜!@#$%^ & *()」的操作,那麼它會接受字符串爲好,並且不會拋出錯誤,即使preg_match == false的結果。

+1

[文檔](http://php.net/manual/en/function.preg-match.php):_preg_match()返回1,如果模式匹配給定的主題,則返回0,如果不匹配,則返回0,如果發生錯誤,則爲FALSE._您是否嘗試過比較'!= 0'而不是 – davidkonrad

+0

@davidkonrad:很好知道,但仍然不是預期的結果我確信validateString返回false,但if條件isn t接受它... – TimNguyenBSM

+0

從pregmatch 該函數可能返回布爾FALSE,但也可能返回一個非布爾值,其中 評估爲FALSE。有關更多信息,請閱讀布爾部分。使用=== 運算符來測試此函數的返回值。 嘗試使用===而不是== –

回答

0
$string = trim($string); 

if ($string == null || $string == "") { 
    return false; 
} else { 
    if (preg_match("/[^\.,\-_'\"@?!:;\$#&\+=\sa-zA-Z0-9\(\)]/", $string) == true) { 
     return false; 
    } else { 
     return true; 
    } 
} 

這是更有效的正則表達式,但不是你想要的結果:你檢查幾乎所有的輸入,所以它會匹配「ABCD」,並返回false也是如此。有11個字符具有特殊含義的正則表達式,只有那些和「需要進行轉義:^ $ []()| * + -

0

試試這個: -

<?php 
$string = "tes$%tname"; // invalid string 
//$string = "testname"; // valid string 

if(test($string) == false) 
{ 
    echo "String is invalid"; 
} 


function test($string){ 
    $string = trim($string); 

    if ($string == null || $string == "") { 
     return false; 
    } else { 
     if (preg_match("/[^\.,\-_'\"@?!:;\$#&\+=\sa-zA-Z0-9\(\)]/",$string) == true) { 
      return false; 
     } else { 
      return true; 
     } 
    } 
} 

?> 

PHPFiddle是這裏: - http://phpfiddle.org/main/code/cdu-xg2

相關問題