简体   繁体   中英

Rails JavaScript validations on dynamic nested model fields

I have a nested model form where the user can create a "project" that can include any number of "tasks" which consist of a taks "name" and "description". These tasks get added dynamically by the user using jQuery.

I want to provide client side validations for the fields in each of these tasks, currently I am using the livevalidation plugin.

The problem is that the input fields are given a dynamic id based on the current time since thay have to be unique for Rails to do its stuff when the form is submitted.

The way I see it, I have two options:

  1. Somehow get the javascript validations to accept a wildcard so that every time a task is added, validations can be set against its fields based on the part of its id that does not change.

  2. Create the necessary validation javascript inline at the same time that the task is created.

Would the above work? are there any better options? how would I get an element selected from a partial id match into the validator?

Thanks

I would recommend using the jQuery Validation Plugin . It lets you create validations based on the attribute names instead of their IDs, and you can use the same set of rules for different forms:

validation = { rules: { "name": "required", "description": "required" } }
jQuery("#form-1").validate(validation);
jQuery("#form-2").validate(validation);

If you want to pass explicit ids you can use a function to generate your rules:

function validation_rules(index){
  return {
    rules: {
      "name["+index+"]": "required",
      "description["+index+"]": "required"
    }
  };
}

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