2008-03-21

This validation goes through and validates each individual word in your string. This goes in whatever model you're validating. "Subject" can be any of the symbols in your model and doesn't need the : in front of it.

def validate
	if subject.split.any?{|w| w.length > 26}
		errors.add(:subject, "cannot have words more than 26 consecutive characters")
	end
end

One Response to “Custom validation with rails: words with more than 26 characters”

  1. jessecrouch Says:

    I've modified this slightly from how I originally wrote it. Now you can add links and phrases-like-this or/like/this or+this. It splits at any non-alphanumeric characters and spaces:

    if subject.split(%r{\s+|\W+}).any?{|w| w.length > 26}
    errors.add(:subject, "cannot have words more than 26 consecutive characters")
    end

Leave a Reply