Thursday, May 5, 2011

rails jquery ajax form validation

I'm looking to do some ajax form validation with jquery. Everything is in place and I can return my errors in a json object that looks something like this:

errors => {
"first_name": "cannot be blank",
"password": "cannot be blank",
"last_name": "cannot be blank",
"email": "cannot be blank"}

This works fine if I just want to display the error messages at the top. However I'd also like to do something similar to the built in rails valdation where it surrounds and error fields with a 'fieldWithErrors' div. (actually I just want to append the class 'fieldWithErrors' to the error input)

I'm not sure exactly where the rails magic that finds the appropriate error fields and adds the error div is, but I'm looking for that code so that I can return a json object that has the error message, and the actual ID of the error field so I can update it with the proper class. Of course I can just prepend the object name (user in this case) to the 'field' that is returned in the json object (ie. 'first_name') however I want this to be a generic function that works for any form that i have.

Can anyone point me to the place where the actual ID of the error field is generated. I'd love to be able to do something like @object.errors[:first_name].field_id so I could return a json object similar to the above one, except my key 'first_name' is actually 'user_first_name', the ID of the error field.

From stackoverflow
  • look in actionpack/lib/action_view/helpers/form_helper.rb to see how Rails does it

    Here are the methods in form_helper.rb that determine the tag ID

        def tag_id
          "#{sanitized_object_name}_#{sanitized_method_name}"
        end
    
        def sanitized_object_name
          @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
        end
    
        def sanitized_method_name
          @sanitized_method_name ||= @method_name.sub(/\?$/,"")
        end
    
    brad : Thanks for pointing me in the right direction. Are you familiar with the form_helper file? I can see some where there is a tag_id method but this is in class InstanceTag. I can't figure out how to turn my @user object attributes into the tag_id's

0 comments:

Post a Comment