Check username availability
I have a login form:
<%= 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 a username in the database right after: user-field has lost focus. I can override this event on the form using javascript, but I cannot send a Ruby-AJAX request from javascipt code.
Is it possible to check the username without adding additional controls (buttons, links) in the form?
You can use 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 search for any fields with the data-validate attribute. Then it processes the onBlur event onBlur (the focus is lost in the JavaScript world). The blur handler will send an AJAX request to the URL specified in the data-validate attribute and pass the user parameter with the input value.
Then change your view to add the data-validate attribute with the validation URL:
<%= text_field_tag(:user, :'data-validate' => '/users/checkname') %> Next, add a route:
resources :users do collection do get 'checkname' end end And in the last step, create your check:
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