Topic: Getting specifics on the validations in an AR model

Hello, I've been using Rails for about a year now and am a long-time visitor, first-time poster here.

I've decided to write a plugin that will help users do client-side validation using Javascript, since I noticed there wasn't something like that around.

Somewhat along the lines of Dexagogo's really easy field validation, I want to add CSS classes to field elements that need to be validated, and reference those in a javascript file.
My idea consists of reading the validations on a model (field name, validation function name and error message) and using those to generate the Javascript validations file.
The format of said file would be something like this

Validate(object){
  classes = object.classNames.split(" ")
  for(var i = 0; i < classes.length; i++){
    var current_class = classes[i];
    if(validations[current_class][0](object.value)){
      // it's fine!
    } else {
      // show the errror
    }
  }
}
var validates_presence_of = function(v) {v != '' && v != undefined}
validations['validates_presence_of_name'] = [validates_presence_of, "Needs a name"]

In the view you can then specify CSS classes (like "validates_presence_of_name") to be applied to a form field and add an onchange action like "Validate(this)". Both of which you should do with a FormBuilder ofcourse.

I'm using much the same in a generator template now (to reuse error strings), but it would be really easy to move (most of) it into a plugin that generates the validations hash on the fly.
Unfortunately, I haven't been able to figure out a nice way to retrieve all the validation information that can be applied to a model.

After looking through Dissecting rails validations part 1 and part 2 I've gathered that validation methods add an inheritable Proc to the ActiveRecord::Validations instance. These can then be accessed by run_validations when needed.

I'm kind of confused on what I should extend and where. I thought it might be easier to just parse model source files in my plugin, but that wouldn't be very DRY. I think I'm almost there, I just haven't the foggiest on how to handle those Procs properly. And I have a vague feeling I might be on the wrong track altogether.

So there's my introduction, my idea and my problem.

Would anyone care to share some insights? I think the Javascript model could use a bit of tweaking, too.

Last edited by aczid (2007-09-01 18:34:05)