Drink or code ... Why should you choose ?
Published at Sun, 02 Nov 2008 22:00:00 +0000

Rails : add a validation error

You probably already know (otherwise, I highly invite you to read the Ruby on Rails bases) how easy it is to validate datas with our favorite framework :)

if myDatas.save
    #The datas have been saved
else
    #There's an error. The myDatas.errors contains it.
end

After that, you only need to add some validation parameters for the datas in the model. But now, let's guess others validations cases, a bit particular that doesn't enter in the "normal" case.

You only need to create a new method which will come validate your datas (the example above is completely fake) :

def validates_roxitude(*attribute)
    reg = Regexp.new '/^ruby(.*?)rox$/'
    self.errors.add('rox', 'Hey, Ruby rox. You have to say it !') unless reg.match attribute
end

Here, we declare an error except if the field starts par "ruby" and ends by "rox".

We only need to force the validation with this method for our field and Ruby rox ! ;)

class myModel < ActiveRecord::Base
    validates_roxitude :myField
end

Comments

Post a New Comment

Markdown enabled