summaryrefslogblamecommitdiffstats
path: root/lib/contact.rb
blob: 0a7a449a4351966939246209720c4f06c2498a97 (plain) (tree)
1
2
3
4
5
6
7
8
9
             
                                                              
 


                              


                                    


                              
     
 



                                       
            
                            


                       
               
                
                                       
                                                

       

                                                 


                                       
                                         

       

                                                         

       

                                                         

       






                                       
     







                                                                           
   
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