使用带有正则表达式的ajax进行表单验证

时间:2022-11-24 14:50:55

Right now i am using ajax to get the value from input field on key press and match it with the data in mysql,if the data is unique then it will make the border green and mark tick else red border and cross. now i want to add regex to validate the input and restrict it.

现在我使用ajax从按键上的输入字段中获取值并将其与mysql中的数据匹配,如果数据是唯一的,则它将使边框变为绿色并标记其他红色边框和交叉。现在我想添加正则表达式来验证输入并限制它。

function username_check() {
        var username = $('#warden_id').val();
        if (username == "" || username.length < 4) {
            $('#warden_id').css('border', '1px #CCC solid');
            $('#tick').hide();
        } else {

            jQuery.ajax({
                type: "POST",
                url: "check.php",
                data: 'username=' + username,
                cache: false,
                success: function (response) {
                    if (response == 1) {
                        $('#warden_id').css('border', '1px #C33 solid');
                        $('#tick').hide();
                        $('#cross').fadeIn();
                    } else {
                        $('#warden_id').css('border', '1px #090 solid');
                        $('#cross').hide();
                        $('#tick').fadeIn();
                    }

                }
            });
        }

regex i want to use to validate data

正义表达我想用来验证数据

/^[a-zA-Z\s]+$/

1 个解决方案

#1


2  

Just for information you should not validate User code on the clientside. Always treat input from the client as evil

仅供参考,您不应在客户端验证用户代码。始终将来自客户端的输入视为邪恶

I changed the regex so that the min length (username.length < 4) of the Username is included

我更改了正则表达式,以便包含用户名的最小长度(username.length <4)

 function username_check() {
    var username = $('#warden_id').val();

    // if / else has been turned
    if (username.match(/^[a-zA-Z\s]{4,}$/)) {
        ...
    } else {
        $('#warden_id').css('border', '1px #CCC solid');
        $('#tick').hide();
    }
     ...

...

#1


2  

Just for information you should not validate User code on the clientside. Always treat input from the client as evil

仅供参考,您不应在客户端验证用户代码。始终将来自客户端的输入视为邪恶

I changed the regex so that the min length (username.length < 4) of the Username is included

我更改了正则表达式,以便包含用户名的最小长度(username.length <4)

 function username_check() {
    var username = $('#warden_id').val();

    // if / else has been turned
    if (username.match(/^[a-zA-Z\s]{4,}$/)) {
        ...
    } else {
        $('#warden_id').css('border', '1px #CCC solid');
        $('#tick').hide();
    }
     ...

...