def validate_string(typedef, value): """ Validate a string, check length. """ # Check to see if the typedef has any pattern restrictions. If it does, # then match against all of the patterns. If it matches any # of the patterns (i.e. not all of the patterns), then the argument # value is considered to be valid. patterns = typedef.get('pattern') if patterns: # If it's a single pattern convert it to a tuple, so we can handle # it in a common way below. Note that we don't use collection.Sequence # in the isinstance call because strings are sequences if command._is_string(patterns): patterns = (patterns,) for pattern in patterns: if re.match(pattern, str(value)): break else: command._raise_argument_validation_exception(typedef, value, 'invalid string pattern') # Check for any length restrictions. This can be a single scalar length or # a single length range or a sequence of either of those. For scalar lengths # the length must match it exactly. For length ranges the length of the argument # must be between the two values (inclusive). For a list of length specs, the # length must match any of the lengths (either scalar or range) in the list. lengths = typedef.get('length') if lengths: if command._is_single_range(lengths): lengths = (lengths,) for length in lengths: command._check_one_range(length) if isinstance(length, numbers.Integral): if len(value) == length: break if len(value) >= length[0] and len(value) <= length[1]: break else: command._raise_argument_validation_exception(typedef, value, 'invalid string length') return value
def validate_integer_range(typedef, value, ranges): # Check for any range restrictions. This can be a single scalar value or # a single range or a list/tuple of a combination of those. For scalar ranges # the arg must match it exactly. For ranges the value of the argument # must be between the two values (inclusive). For a list of range specs, the # value must match any of the lengths (either scalar or range) in the list. if ranges: if command._is_single_range(ranges): ranges = (ranges,) for r in ranges: command._check_one_range(r) if isinstance(r, numbers.Integral): if value == r: break else: lower_boundary = command._convert_range_boundary(r[0], value) upper_boundary = command._convert_range_boundary(r[1], value) if value >= lower_boundary and value <= upper_boundary: break else: command._raise_argument_validation_exception(typedef, value, 'value is outside specified ' 'range: (%d-%d)' % (r[0], r[1]))