Using the remote function of jquery validation

后端 未结 8 684
逝去的感伤
逝去的感伤 2020-12-16 03:12

I\'m trying to figure out how I can turn this:

$(\'#username\').blur(function(){
    $.post(\'register/isUsernameAvailable\', 
           {\"username\":$(\'#         


        
8条回答
  •  情话喂你
    2020-12-16 03:48

    I needed to do remote validation in a rails project recently and struggled to send the correct response from server side if the input is invalid. At the end, the solution was quite simple.

    If the server side check returns true, you can send true or "true", else you can return any string like "The email already exists" or "Email does not have valid MX records". This string will be displayed as the validation message on the form. The only catch is that the message string returned from server side should be valid JSON and should be in this format - ["The email already exists"].

    Some explanation on how I debugged and found the solution: Please see below the remote method in jquery.validate.js. I had added log statements and an error function to the ajax call to debug. When I returned a normal string from server side, a jQuery.parseJson error was thrown.

    // http://jqueryvalidation.org/remote-method/
    
    remote: function( value, element, param ) {
        if ( this.optional( element ) ) {
            return "dependency-mismatch";
        }
    
        var previous = this.previousValue( element ),
            validator, data;
    
        if (!this.settings.messages[ element.name ] ) {
            this.settings.messages[ element.name ] = {};
        }
        previous.originalMessage = this.settings.messages[ element.name ].remote;
        this.settings.messages[ element.name ].remote = previous.message;
    
        param = typeof param === "string" && { url: param } || param;
    
        if ( previous.old === value ) {
            return previous.valid;
        }
    
        previous.old = value;
        validator = this;
        this.startRequest( element );
        data = {};
        data[ element.name ] = value;
    
        $.ajax( $.extend( true, {
            url: param,
            mode: "abort",
            port: "validate" + element.name,
            dataType: "json",
            data: data,
            context: validator.currentForm,
            success: function( response ) {
                console.log("response is "+response);
                var valid = response === true || response === "true",
                    errors, message, submitted;
                console.log("valid is "+valid);
                validator.settings.messages[ element.name ].remote = previous.originalMessage;
                if ( valid ) {
                    submitted = validator.formSubmitted;
                    validator.prepareElement( element );
                    validator.formSubmitted = submitted;
                    validator.successList.push( element );
                    delete validator.invalid[ element.name ];
                    validator.showErrors();
                } else {
                    errors = {};
                    message = response || validator.defaultMessage( element, "remote" );
                    console.log("else message is "+message);
                    errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
                    validator.invalid[ element.name ] = true;
                    console.log("else errors[ element.name ] "+errors[ element.name ]);
                    validator.showErrors( errors );
                }
                previous.valid = valid;
                validator.stopRequest( element, valid );
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        }, param ) );
        return "pending";
    }
    

提交回复
热议问题