我正在收集表單數據,並通過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的結果。
[文檔](http://php.net/manual/en/function.preg-match.php):_preg_match()返回1,如果模式匹配給定的主題,則返回0,如果不匹配,則返回0,如果發生錯誤,則爲FALSE._您是否嘗試過比較'!= 0'而不是 – davidkonrad
@davidkonrad:很好知道,但仍然不是預期的結果我確信validateString返回false,但if條件isn t接受它... – TimNguyenBSM
從pregmatch 該函數可能返回布爾FALSE,但也可能返回一個非布爾值,其中 評估爲FALSE。有關更多信息,請閱讀布爾部分。使用=== 運算符來測試此函數的返回值。 嘗試使用===而不是== –