DragonWar% 2015-12-02 16:05 采纳率: 0%
浏览 34

Rails AJAX表单验证

Where is the best place to implement form validation for an AJAX form in rails when I'm not using a model for the form? And how would I go about implementing it?

My form being submitted needs to check if an IP address exists and is valid before the methods in the controller are run. If the IP is invalid, I'd like to let the user know via a flash[:danger] message.

views/tools/forms/_ping.html.erb

<%= form_tag ping_tool_path(1), role: "form", class: "form-inline form_ip", name: "ping-form", method: "post", remote: true do %>
    <%= text_field_tag :ip, params[:ip], class: "form-control" %>
    <%= submit_tag "Ping", name: nil, class: "btn btn-default" %>
<% end %>

views/tools/ping.js.erb

$(".output").html("<%= j (@results) %>");

controllers/tools_controller.rb

def ping
    ping_host(params[:ip])
    save_host(params[:ip])

    # AJAX
    respond_to do |format|
      format.js
    end
end
  • 写回答

1条回答 默认 最新

  • YaoRaoLov 2015-12-02 16:27
    关注

    It will depend on how much time and how much scalable your application is or intends to be.

    For a more scalable solution, I would use active_interaction gem, create a new interaction and put the validation on it.

    here is the docs https://github.com/orgsync/active_interaction

    If you want a easier solution you can always create a private method on the controller that validates the ip.

    edited

        private
    
        require 'resolv'
    
        def valid_ip?(ip)
          case ip
          when Resolv::IPv4::Regex
            return true
          when Resolv::IPv6::Regex
            return true
          else
            return false
          end
        end
    

    inspired on this article http://spin.atomicobject.com/2013/08/28/ruby-ip-address-regex/

    edit 2

    linking both parts

    in your controller

        def ping
            if valid_ip?(params[:ip])
              ping_host(params[:ip])
              save_host(params[:ip])
              render json: { message: "sucess" }
            else
              render json: { errors: "Invalid Ip" }, status: 422
            end
        end
    

    javascript

        <script>
          $(document).ready(function(){
            $('.form_ip').on('ajax:success',function(e, data, status, xhr){
              // success message
              alert("success");
            }).on('ajax:error',function(e, xhr, status, error){
              // errors handler
              var errors = $.parseJson(xhr.response_text).errors;
              alert(errors);
            });
          });
        </script>
    

    source -> http://travisjeffery.com/b/2012/04/rendering-errors-in-json-with-rails/

    And If you want to validate before the user submits too, take a look at html5 input pattern attribute http://www.w3schools.com/tags/att_input_pattern.asp

    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀