dqz30992 2013-08-29 00:22
浏览 66
已采纳

通过AJAX将特殊字符传递给PHP

I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.

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 Validation

$postData = $_POST;

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

PHP Filter

//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;
        }
    }
}

On an empty string it prints error to screen just fine. But if I do something like "~!@#$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of preg_match == false.

  • 写回答

2条回答 默认 最新

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

    That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)