Check username availability using jquery and Ajax in rails

前端 未结 2 610
囚心锁ツ
囚心锁ツ 2020-12-29 17:11

I am using rails with jquery and ajax to check the availability of username. I am using the following plugin for jquery validation purpose.

https://github.com/p

相关标签:
2条回答
  • 2020-12-29 17:22

    To check the Username/Email Availability do the following:

    Using the https://github.com/posabsolute/jQuery-Validation-Engine

    edit the validationsEngines-en.js file for the AJAX calls, one for the email will look like the following:

                "ajaxEmailAvailable": {
                    "url": "/route_to_send_the_parameters",
                    // you may want to pass extra data on the ajax call
                    "alertTextOk": "* This email is available",
                    "alertText": "* This email is already taken",
                    "alertTextLoad": "* Validating, please wait"
                },   
    

    Make sure you configure your routes.rb file to match the route you want to use, the default action with the call is a GET HTTP Request.

    Next set up the proper action in your controller to handle the request (I included a helper in the Application Controller so that the input value can be sanitized before queried in the database:

    CONTROLLER HANDLING THE REQUEST

      def username_availability
         scrubb = help.sanitize(params[:fieldValue], :tags => '')
         user = User.find_by_email(scrubb)
            if user.blank?
                render :json =>  ["INPUT_ID", true , ""]
            else
                render :json =>  ["INPUT_ID", false , "This email is already taken"]
            end
       end
    

    If you are unsure of the proper INPUT ID, watch the server logs for the parameters passed during the call and do a simple copy-paste. By default the request passes the INPUT ID and INPUT VALUE.

    To gain access to this helper add the following:

    APPLICATION CONTROLLER

      def help
        Helper.instance
      end
    
      class Helper
        include Singleton
        include ActionView::Helpers::TextHelper
      end
    

    Now on the form itself, your input should read as the following:

    <%= c.text_field :email, "data-validation-engine"=>"validate[required, custom[email], ajax[ajaxEmailAvailable]]" %>
    

    As per the proper functionality always place the AJAX call as the last validation.

    Don't forget to include jquery.js, jquery.validationEngine-en.js, jquery.validationEngine.js and validationEngine.jquery.css in the head of the document [in that order of js] and to call a

    <script type="text/javascript">$(function() {$("#FORM_ID").validationEngine();});</script>
    

    If you want to do this for username, just edit the above appropriately.

    0 讨论(0)
  • 2020-12-29 17:23

    I am adding the answer. Sorry for the delay guys.

    First credit to the plugin:https://github.com/posabsolute/jQuery-Validation-Engine . Used the plugin for validations in the application.

    In the view, i had

    <%= f.username_field :username, :id => 'free-user', :placeholder=>'User Name', :class => "validate[required, ajax[ajaxUserCall]]", "data-prompt-position" => "topLeft:0,9"%>
    

    In the same view, in java script:

    <script type="text/javascript">
     $(document).ready(function(){
      $("#free-user").bind("jqv.field.result", function(event, field, errorFound, prompText){
        if(errorFound){
            $(".continue").attr("disabled", false);  // .continue is a button
        } else{
            $(".continue").attr("disabled", true);
        }
      })
     });
    </script>
    

    In routes.rb i have the following route.

    match '/check-user' =>"users#check_user"  // creating route for ajax call
    

    In jquery.validationEngine-en.js file i have following:

    "ajaxUserCall": {
                    "url": "/check-user",
                    // you may want to pass extra data on the ajax call
                    "alertText": "* This user is already taken",
                    "alertTextLoad": "* Validating, please wait"
                },
    

    In users controller, i have the following method

    def check_user
      user = params[:fieldValue]
      user = User.where("username = ?", username).first
      if user.present?
        render :json =>  ["free-user", false , "This User is already taken"]
      else
        render :json =>  ["free-user", true , ""]
      end
    end
    
    0 讨论(0)
提交回复
热议问题