summaryrefslogtreecommitdiffstats
path: root/lib/contact.rb
blob: 0a7a449a4351966939246209720c4f06c2498a97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Contact
  attr_reader :name, :street, :postcode, :city, :phone, :email

  def initialize(params = nil)
    if params
      @name = params['name']
      @street = params['street']
      @postcode = params['postcode']
      @city = params['city']
      @phone = params['phone']
      @email = params['email']
    end
  end

  def addr
    "#{@street}, #{@postcode} #{@city}"
  end

  def valid?
    validate! unless @errors
    @errors.length == 0
  end

  def validate!
    @errors = []
    if @name.nil? || @name.strip.empty?
      @errors << "Du må oppgi en kontaktperson"
    end

    unless valid_postcode
      @errors << "Du må oppgi et gyldig postnr."
    end

    if @city.nil? || @city.strip.empty?
      @errors << "Du må oppgi poststed."
    end

    unless valid_phone?
      @errors << "Telefonnummer mangler eller er ugyldig"
    end

    unless valid_email?
      @errors << "E-postadresse mangler eller er ugyldig"
    end

    @errors
  end

  private

  def valid_postcode
    @postcode && @postcode =~ /^\d{4}$/
  end

  def valid_email?
    @email && @email =~ /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]{1,63}\.)+[A-Z]{2,}$/i
  end

  def valid_phone?
    @phone && @phone =~ /^\+*[0-9- ]{8,}$/
  end
end