简体   繁体   中英

target HTML 'name' attribute a rails form builder with Jquery

I've created a multi-step form based off of the tutorial here . It integrates Jquery Validation in the process to make sure that the data is clean before it hits the server. The validation and multi-step form all work as desired, but since Jquery Validation targets the HTML name tags instead of the id I had to change them manually in order to get the validation to work.

rules: {
                      registrant_first_name: {
                        required: true,
                        minlength: 2,
                    },

                    ...
        },

And in the form helper:

<%= f.text_field :first_name, name: 'registrant_first_name', class: 'form-control' %>

Yet, while this works this sends my params out of the registrant controller and I'd need to re-configure the model to accept the new params. The form responds by rejecting the data and saying the fields are blank (which they technically are)

registrant_first_name: John
registrant_last_name: Doe
registrant_email: johndoe@msn.com

While I'm pretty sure I can fix this problem by simply re-configuring the registrants model to accept the parameters, I'm wondering is there a way to configure the Jquery Validation rules to target the name attribute generated by the forms helper? (currently it throws an error)

rules: {
                      registrant[first_name]: {
                        required: true,
                        minlength: 2,
                    },

                    ...
        },

And if not, is there any harm in configuring the model to allow these parameters that will no longer belong to the registrants hash?

I'm wondering is there a way to configure the Jquery Validation rules to target the name attribute generated by the forms helper? (currently it throws an error)

Yes. Simply surround the name with quotation marks.

rules: {
    'registrant[first_name]': {
        required: true,
        minlength: 2,
        ....

Documentation: Fields with complex names (brackets, dots) :

"If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM