RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

What is the Rails 3 Way to do a form field validation prior to submission?

I basically want to prevent searches that are less than 3 characters long.

In Rails 2.x, I would just do this in an onClick event. I understand how to handle AJAX requests and responses in Rails 3 now, but wouldn't using the onClick event be considered obtrusive in Rails 3?

Upvotes: 2

Views: 573

Answers (2)

RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

Got it! I put this code in application.js:

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function() {
    $("#search_submit").click(function() {
        if ($("#search_value").val().length < 3) {
            alert("You must supply 3 or more characters in your search.");
            return false;
        }
    })
})

My form is:

  <%= form_for(@search, { :remote => true, :html => { :id => 'left', :class => "custom-border" } }) do |f| %>
    <h2><%= f.label :value, "Search By Part or Interchange #" %></h2>
    <p><%= f.text_field :value %></p>
    <p class="button"><%= f.submit "Search" %></p>
  <% end %>

Voilá!

Upvotes: 0

balu
balu

Reputation: 3689

Yup, onclick would indeed be considered obtrusive. You might want to use a third-party validation library in javascript. It could work something like this:

<form ... class="validated">
  <input type="text" name="name" data-validation="presence=true,format=/[a-zA-Z0-9\s]+/" />
  <input type="submit" value="Send" />
</form>

<script language="javascript">
  $('form.validated').live('submit', function() {
    var data = $(this).serializeArray();
    var errors = [];
    $(this).find('input').each(function() {
      var input = $(this);
      $.each($(this).attr('data-validation').split(','), function(validation) {
        var type, param = validation.split("=");
        if(type == "presence") {
          if(input.val() == "") errors += input.attr('name') + " is empty";
        } else if(type == "format") {
          ...
        }
    });
    return (errors.length == 0);
  });
</script>

(Just some rough code out of my head. Lots of caveats there.)

But instead of writing all that, perhaps you just want to use: http://github.com/jzaefferer/jquery-validation

Upvotes: 2

Related Questions