Validate access to object field

Suppose I have a Model called House with a field called name

how can I validate the name field, I tried name in the validate method
but
it doesn’t work, i tried name, :name, House.name, I don’t know how I can
validate this field within a validate method, I don’t know how I can
access it.

class ContractGroup < ActiveRecord::Base
has_and_belongs_to_many :locatel_content_groups

protected
def validate
#name.gsub(" ", “”) this doesn’t work name is nil

errors.add_on_empty(:name) # this work

reg = /[a-z]*/
unless reg.match(name) #this doesn’t work, name is nil but the match
function return true !
errors.add(:name, “has invalid format”)#this doesn’t work
end
end

end

Ok, now I manage to access field with self.name

But there is still the regular expression to create :

I need name composed of
a to z
A to Z
dash -
underscore _

I tried different combination without success

How can I test this

David N. wrote:

Ok, now I manage to access field with self.name

But there is still the regular expression to create :

I need name composed of
a to z
A to Z
dash -
underscore _

match /[a…z A…Z - _]/
or /[a…z - _]
/i

On 6 Aug 2008, at 16:32, Justin To wrote:

underscore _

match /[a…z A…Z - _]/
or /[a…z - _]
/i

That doesn’t work, for two reasons:

    • is a special character in a character class, so it has to be the
      first character in the character class (ie [-…])
  1. That aside, that regular expression will match any string, because
    all it says is ‘the string contains 0 or more of those characters’.
    You need to anchor it: \A matches the beginning of a string \z matches
    the end:
    so
    /\AHi\z/ will match the string Hi but not the string Hiatus, whereas /
    Hi/ will match both (there are other anchors with slightly different
    semantics: ^ and $ match the beginning and end of lines, and \Z
    matches the end of the string, excluding any trailing \n

Fred

You’ve posted basically the same question (or line-of-thought) in
THREE separate threads. Please don’t do this as it’s hard to keep
track of THREE threads.