Supersonic
Supersonic

Reputation: 430

Rails validations using errors.add

I have a separate method in my model to validate like this:

validate :validate_id

def validate_id
    errors.add(:base, "Id Should Not Blank") if self.project_id.blank?
end

I need to perform a validation which would be like this:

validates_format_of :project_id, :with => /^(?!\d+$)[a-z0-9-_]*$/

which would validate letters and numbers with only underscore and dash and no spaces between them.

Is there any possible way to use it in my method validate_id.

Thanks in advance

Upvotes: 0

Views: 69

Answers (1)

shweta
shweta

Reputation: 8169

Try:

def validate_id
  errors.add(:base, "Id Should Not Blank") if /^(?!\d+$)[a-z0-9-_]*$/.match(self.project_id).nil?
end

Upvotes: 1

Related Questions