Using the remote function of jquery validation

后端 未结 8 673
逝去的感伤
逝去的感伤 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:30
    Jquery Code: 
     rules: {
            email: {
                    required: true,
                    maxlength: 50,
                    email: true,
                     remote: {
            url: "<?php echo base_url('user/email_check') ?>",
            type: "post",
            data: {
              email: function() {
                return $( "#email" ).val();
              }
            }
          }
                },     
        },
         messages: {
          email: {
              required: "E-mailadres",
              email: "Please enter valid email",
              maxlength: "The email name should less than or equal to 50 characters",
              remote: jQuery.validator.format("{0} is already taken.")
            },
        },
    
    PHP Code:
      if($results->num_rows == 0)
        {
            echo "true";  //good to register
        }
        else
        {
            echo "false"; //already registered
        }
    
    0 讨论(0)
  • 2020-12-16 03:36

    Well I dunno bout your plugin concept specifically but I gather you want it to check to see with that plugin if the username is greater than 6 or less than 12. Which from your core example with jQuery without the plugin it would be as simple as adding one little if-else to the concept.

    $('#username').blur(function(){
        if($('#username').val().length < 6 || $('#username').val().length > 12)
        {
            alert('Username must be between 6 and 12 characters');
        }
        else
        {
           $.post('register/isUsernameAvailable', 
                  {"username":$('#username').val()}, 
                  function(data){
                      if(data.username == "found"){
                          alert('username already in use');
                      }
                  }, 'json');
        }
    });
    
    0 讨论(0)
  • 2020-12-16 03:37

    I know it's too late, but this could help other people.

    The remote method is meant to recieve a Json string, so your server side should be returning something like this to the method...

    echo(json_encode(true)); // if there's nothing matching
    echo(json_encode(false));
    

    This is an example of the JS code that I wrote while trying to validate user's nickname.

    $(document).ready(function(){
                $('#form').validate({
                rules: {
                    user_nickname: {
                        remote: {
                            url: "available.php",
                            type: "post",
                            data: {
                              user_nickname: function() {
                                return $( "#user_nickname" ).val();
                              }
                            }
                          }               
                    }
                },
                messages:{
                    user_nickname: {
                        remote: "Username already taken"
                    }
                }
            });});
    

    Hope it helps someone, it helped me.

    0 讨论(0)
  • 2020-12-16 03:39

    I think I am too late to reply. but our code is very easy for all

    Validation Code

    rules: {
                session: {
                   required: true,
                    remote: {
                        url: "<?php echo base_url('setting/session_setting/checkSession'); ?>",
                        type: "post",
                        data: {
                          session: function() {
                            return $( "#sessionInput" ).val();
                          }
                        }
                      }
                },
            },
    

    Controller Code

    public function checkSession()
        {
            $response = array();
            $session = $this->input->post('session');
    
            $check = $this->dm->checkData('session','session',array('session'=>$session));
    
            if($check)
            {
                echo(json_encode("Session Already Exist")); 
            }
            else
            {
                echo(json_encode(true)); 
            }
        }
    

    Model Code

    public function checkData($data,$tablename,$where)
        {
            $query = $this->db->select($data)
                     ->from($tablename)
                     ->where($where)
                     ->get();
            if($query->num_rows() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    
    0 讨论(0)
  • 2020-12-16 03:40

    I realize this is old but I had a hard time getting this working as well and wanted to share what worked for me.

    Client-Side form validation code:

    $('#frmAddNew').validate({
    onkeyup: false,
    rules: {
        ADID: {
            required: true,
            alphanumeric: true,
            maxlength: 10,
            remote: {
                url: "ADIDValidation.cshtml",
                type: "post",
                dataType: "json",
                dataFilter: function (data) {
                    if (data) {
                        var json = $.parseJSON(data);
                        if (json[0]) {
                            return JSON.stringify(json[0].valid) /* will be "true" or whatever the error message is */
                        }
                    }
                },
                complete: function (data) {
                   /* Additional code to run if the element passes validation */
                    if (data) {
                        var json = $.parseJSON(data.responseText);
                        if (json[0]) {
                            if (json[0].valid === "true") {
                                $('#FirstName').val(json[0].FirstName);
                                $('#LastName').val(json[0].LastName);
                            }
                        }
                    }
                }
            }
        }
    },
    messages: {
        ADID: {
            required: "Please Enter an ADID of the Employee",
            alphanumeric: "The ADID Can Only Contain Letters and Numbers",
            maxlength: "ADID For User's Current Permissions Must Be 10 Characters or Less"
        }
    },
    submitHandler: function (form) {
        form.submit();
    },
    errorContainer: $('section.errorCon'),
    errorLabelContainer: $('ol', 'section.errorCon'),
    wrapper: 'li',
    showErrors: function (errors) {
        var error = this.numberOfInvalids();
        var message = error == 1
            ? 'You missed 1 field:'
            : 'You missed ' + error + ' fields:';
        $('section.errorCon h3').html(message);
        this.defaultShowErrors();
    }
    });
    

    Server-Side code for ADIDValidation.cshtml (I'm using Razor webpages):

    @{
    
    Layout = null;
    
    if(IsPost)
    {
        var db = Database.Open("<enter connection name>");
        var sql = "<enter sql or stored procedure>";
        var strADID = Request["ADID"];
    
        var result = db.Query(sql, strADID);
        IEnumerable<dynamic> response;
    
        if(result.Any()) 
        {
            @* "true" indicates the element passes validation. Additional data can be passed to a callback function *@
            response = result.Select(x => new
            {
                valid = "true",
                FirstName = x.FirstName,
                LastName = x.LastName
            });
        }
    
        else
        {
            @* The element did not pass validation, the message below will be used as the error message *@
            response = new[] {
                new {valid = "The Employee's ADID '" + strADID.ToString() + "' Is Not Valid. Please Correct and Resubmit"}
            };
        }
    
        Json.Write(response, Response.Output);
    }
    }
    
    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
提交回复
热议问题