Ajax javascript form validation

I want to do some ajax form validation using 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 great if I just want to display error messages at the top. However, I would also like to do something similar to the inline in rails valdation where it surrounds and error fields with a fieldWithErrors field. (actually I just want to add the fieldWithErrors class to the error input)

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

Can anyone point me to the location where the actual error field id is generated. I would like to do something like @ object.errors [: first_name] .field_id so that I can return a json object similar to the previous one, except that my "first_name" key is actually "user_first_name", the id of the error field.

0


source to share


1 answer


take a 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 define 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

      

+1


source







All Articles