简体   繁体   English

检查用户名可用性

[英]Check username availability

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.我想在:user-field 失去焦点之后立即检查数据库中是否有用户名。 I can override this event on the form with javascript, but I can not send Ruby-AJAX request from javascipt code.我可以使用 javascript 在表单上覆盖此事件,但我无法从 javascipt 代码发送 Ruby-AJAX 请求。

Is there any way to check username without adding additional controls (buttons, links) on the form?有什么方法可以检查用户名而不在表单上添加额外的控件(按钮、链接)?

You can use some JavaScript (this one written with jQuery) for AJAX cheking:您可以使用一些 JavaScript (这是用 jQuery 编写的)来检查 AJAX :

$(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 .此 JavaScript 将查找具有属性data-validate的任何字段。 Then it assings onBlur event handler (focus lost in JavaScript world).然后它调用onBlur事件处理程序(焦点在 JavaScript 世界中丢失)。 On blur handler will send AJAX request to the URL specified in data-validate attribute and pass parameter user with input value.模糊处理程序将向data-validate属性中指定的 URL 发送 AJAX 请求,并使用输入值传递参数user

Next modify your view to add attribute data-validate with validation URL:接下来修改您的视图以添加属性data-validate和验证 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.如果您不想使用现有的 jquery 插件从头开始编写,这是验证 forms 的一种友好方式。 Check it out and if you like it let me know!看看,如果你喜欢,请告诉我!

Check username availability using jquery and Ajax in rails 在 rails 中使用 jquery 和 Ajax 检查用户名可用性

For what reason can you not send an ajax request from javascript code?为什么不能从 javascript 代码发送 ajax 请求?

The best way would be to send a GET ajax request when the focus is lost.最好的方法是在失去焦点时发送 GET ajax 请求。 The get request could then return true or false and your javascript could then reflect this on the page.然后获取请求可以返回真或假,然后您的 javascript 可以在页面上反映这一点。

The solution that @Viacheslav has, works fine and my answer is a combination of his and my own changes (especially JS) part. @Viacheslav 拥有的解决方案运行良好,我的回答是结合了他和我自己的更改(尤其是 JS)部分。

We will be using Ajax in order to achieve this.我们将使用Ajax来实现这一点。

Lets first create our function in the controller让我们首先在 controller 中创建我们的 function

def checkname
  if !User.find_by_display_name(params[:dn])
    render json: {status: 200}
  else
    render json: {status: 409}
  end
  return
end

and then adding our routes in routes.rb然后在routes.rb中添加我们的routes

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

Now lets gets our hand on the view.现在让我们来看看这个视图。 Below you'll see the input:下面你会看到输入:

.field
  = f.text_field :display_name, onblur: "checkDisplayName.validate(this.value)"
  %p.error-name.disp-none username exists

And now by help of JS we get the magic rolling.现在在JS的帮助下,我们得到了神奇的效果。 Blow JS has few functions. Blow JS的功能很少。 validate does the actually validation. validate进行实际验证。 getStatus is our Ajax call to get the status and we use showError & disableSubmitButton to our form a bit more production ready to show errors and disabling the submit button. getStatus是我们的Ajax调用来获取状态,我们使用showErrordisableSubmitButton对我们的表单进行更多的生产准备以显示错误并禁用提交按钮。

var checkDisplayName = {
  validate: function(dn){
    checkDisplayName.getStatus(dn).then(function(result) {
      if (!!result){
        if (result.status != 200){
          checkDisplayName.disableSubmitButton(true);
          checkDisplayName.showError();
        } else{
          checkDisplayName.disableSubmitButton(false);
        }
      }
    });
    return false;
  },
  getStatus: async (dn) => {
    const data = await fetch("/pages/checkname?dn=" + dn)
      .then(response => response.json())
      .then(json => {
        return json;
      })
      .catch(e => {
          return false
      });
    
    return data;
  },
  showError: function() {
    let errEl = document.getElementsByClassName('error-name')[0];
    if (!!errEl) {
      errEl.classList.remove("disp-none");
      window.setTimeout(function() { errEl.classList.add("disp-none"); },3500);
    }
  },
  disableSubmitButton: function(status){
    let button = document.querySelector('[type="submit"]');
    button.disabled = status;
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM