jQuery Validation - prevent submit on remote

旧时模样 提交于 2020-02-25 08:07:11

问题


I need to prevent form from submitting when remote call returns true as result. How can I do this?

The JS code:

var userForm = $('#user-form');

userForm.validate({
    rules : {
        email : {
            email: true,
            remote: {
                url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
                type: 'POST',
                data: function(){
                    return $('#email').val()
                },
                complete: function(data){
                    if(data.responseText.trim() == 'true'){
                        return false;
                    }
                }
            }
        }
    }
});

Server side:

public function isUniqueEmail()
    {
        $result = $this->users->isUniqueEmail($this->input->post('email'));

        if($result):
            echo false;
        else:
            echo true;
        endif;
    }

回答1:


Quote OP:

"I need to prevent form from submitting when remote call returns true as result."

That's backwards. You would return false to block the submit and trigger the validation message.

You don't need the data option since the plugin sends the field value by default. You also don't need the complete option as the plugin captures the server response automatically.


JavaScript:

var userForm = $('#user-form');
userForm.validate({
    rules: {
        email: {
            email: true,
            remote: {
                url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
                type: 'POST'  // default is GET
            }
        }
    }
});

Server-side:

public function isUniqueEmail()
{
    $result = $this->users->isUniqueEmail($this->input->post('email'));

    if($result):
        // setting message in PHP allows you to dynamically have any message
        echo json_encode('name is already taken');
    else:
        echo true;
    endif;
}

ALTERNATE

(Custom error message set in JavaScript)

JavaScript:

var userForm = $('#user-form');
userForm.validate({
    rules: {
        email: {
            email: true,
            remote: {
                url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
                type: 'POST'  // default is GET
            }
        }
    },
    messages: {
        email: {
            remote: "name is already taken"
        }
    }
});

Server-side:

public function isUniqueEmail()
{
    $result = $this->users->isUniqueEmail($this->input->post('email'));

    if($result):
        echo false;
    else:
        echo true;
    endif;
}

DOCUMENTATION: http://jqueryvalidation.org/remote-method/



来源:https://stackoverflow.com/questions/25649529/jquery-validation-prevent-submit-on-remote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!