Check username availability

后端 未结 3 1512
甜味超标
甜味超标 2020-12-24 04:25

I have a form to user login:

<%= form_tag(@action, :method => \"post\", :name => \'signup\' ,:onSubmit => \'return validate();\') do %>    
           


        
相关标签:
3条回答
  • 2020-12-24 04:29

    For what reason can you not send an ajax request from javascript code?

    The best way would be to send a GET ajax request when the focus is lost. The get request could then return true or false and your javascript could then reflect this on the page.

    0 讨论(0)
  • 2020-12-24 04:46

    You can use some JavaScript (this one written with jQuery) for AJAX cheking:

    $(function() {
        $('[data-validate]').blur(function() {
            $this = $(this);
            $.get($this.data('validate'), {
                user: $this.val()
            }).success(function() {
                $this.removeClass('field_with_errors');
            }).error(function() {
                $this.addClass('field_with_errors');
            });
        });
    });
    

    This JavaScript will look for any fields with attribute data-validate. Then it assings onBlur event handler (focus lost in JavaScript world). On blur handler will send AJAX request to the URL specified in data-validate attribute and pass parameter user with input value.

    Next modify your view to add attribute data-validate with validation URL:

    <%= text_field_tag(:user, :'data-validate' => '/users/checkname') %>
    

    Next add route:

    resources :users do
      collection do
        get 'checkname'
      end
    end
    

    And last step create your validation:

    class UsersController < ApplicationController
      def checkname
        if User.where('user = ?', params[:user]).count == 0
          render :nothing => true, :status => 200
        else
          render :nothing => true, :status => 409
        end
        return
      end
    
      #... other controller stuff
    end
    
    0 讨论(0)
  • 2020-12-24 04:52

    I answered this in another post.

    It is a friendly way for validating forms if you do not want to write it all from scratch using an existing jquery plugin. Check it out and if you like it let me know!

    Check username availability using jquery and Ajax in rails

    0 讨论(0)
提交回复
热议问题