Module: JSS::Validate

Defined in:
lib/jss/validate.rb

Overview

A collection of methods for validating values. Mostly for ensuring the validity of data being set as attributes of APIObject subclass instances.

Some of these methods can take multiple input types, such as a String or an Array. All of them will either raise an exception if the value isn’t valid, or will return a standardized form of the input (e.g. an Array, even if given a String)

Constant Summary collapse

MAC_ADDR_RE =

The regular expression that matches a valid MAC address.

/^[a-f0-9]{2}(:[a-f0-9]{2}){5}$/i

Class Method Summary collapse

Class Method Details

.ip_address(val) ⇒ String

Validate the format and content of an IPv4 address

Parameters:

  • val (String)

    The value to validate

Returns:

  • (String)

    The valid value

Raises:



59
60
61
62
63
64
65
66
# File 'lib/jss/validate.rb', line 59

def self.ip_address(val)
  ok = true
  parts = val.strip.split '.'
  ok = false unless parts.size == 4
  parts.each { |p| ok = false unless p.jss_integer? && p.to_i < 256 }
  raise JSS::InvalidDataError, "Not a valid IPv4 address: '#{val}'" unless ok
  val
end

.mac_address(val) ⇒ String

Validate the format and content of a MAC address

Parameters:

  • val (String)

    The value to validate

Returns:

  • (String)

    The valid value

Raises:



48
49
50
51
# File 'lib/jss/validate.rb', line 48

def self.mac_address(val)
  raise JSS::InvalidDataError, "Not a valid MAC address: '#{val}'" unless val =~ MAC_ADDR_RE
  val
end

.unique_identifier(klass, identifier, val, api: JSS.api) ⇒ Object

Validate that a value doesn’t already exist for a given identifier of a given class

Parameters:

  • klass (JSS::APIObject)

    A subclass of JSS::APIObject, e.g. JSS::Computer

  • identifier (Symbol)

    One of the keys of an Item of the class’s #all Array

  • val (Object)

    The value to check for uniqueness

Returns:

  • (Object)

    the validated unique value

Raises:



78
79
80
81
# File 'lib/jss/validate.rb', line 78

def self.unique_identifier(klass, identifier, val, api: JSS.api)
  raise JSS::AlreadyExistsError, "A #{klass} already exists with #{identifier} '#{val}'" if klass.all(:refresh, api: api).map { |i| i[identifier] }.include? val
  val
end