Last post we looked at how to setup a virtual attribute. This post we’ll look at how to validate it.

Normal rails model validation looks something like this:

  validates :password_checked, :presence => true
  validates :password_checked, :presence => { :message => " is required" }

But that won’t work here because the :password_checked is always going to be present and the error message won’t look great because it will simply be appended to the default.

Instead we can do this:

  validate do |user|
    if user.password_checked == "0"
      user.errors[:base] << "Oops - could you click confirm password checkbox please."

if the value of the checkbox coming to us is “0” add our own custom error message.

And you can add an rspec test for your user model as follows:

require 'spec_helper'

describe User do
  before(:each) do
    @attr = { 
      :name => "Example User",
      :email => "",
      :password => "foobar",
      :password_checked => "1",
  it "should require a checked password checkbox" do
    no_password_checked = => "0"))
    no_password_checked.should_not be_valid