'signup' ,:onSubmit => 'return validate();') d...">

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?

+6
source share
3 answers

Why can't you send ajax request from javascript code?

A better way would be to send a GET ajax request when focus is lost. Then the request for receipt can return true or false, and your javascript can then reflect this on the page.

0
source

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 
+35
source

I answered this in another post.

This is a friendly way to validate forms if you don't want to write it all from scratch using your existing jquery plugin. Check it out and if you like it let me know!

Check username availability with jquery and Ajax in rails

0
source

Source: https://habr.com/ru/post/886856/


All Articles