检查用户名可用性

I have a form to user login:

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

I want to check if there is the username in the database immediately after :user-field lost focus. I can override this event on the form with javascript, but I can not send Ruby-AJAX request from javascipt code.

Is there any way to check username without adding additional controls (buttons, links) on the form?

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.

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

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