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
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.
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/
linking both parts
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
<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