Validate the Address record according to what will be valid by the gateway.

 Usage:
  address.valid?     # Returns true/false

  Additionally sets address.errors array to an array of field/error.
170264
def valid?
      @errors = []

      if !INVOICE_TYPE[invoice_type]
        @errors << ['invoice_type', "must be one of #{INVOICE_TYPE.keys.join('/')}"]
      end

      if !invoice_id.nil? && invoice_id !~ GUID_REGEX
        @errors << ['invoice_id', 'must be blank or a valid Xero GUID']
      end

      if invoice_status && !INVOICE_STATUS[invoice_status]
        @errors << ['invoice_status', "must be one of #{INVOICE_STATUS.keys.join('/')}"]
      end

      if line_amount_types && !LINE_AMOUNT_TYPES[line_amount_types]
        @errors << ['line_amount_types', "must be one of #{LINE_AMOUNT_TYPES.keys.join('/')}"]
      end

      unless date
        @errors << ['invoice_date', "can't be blank"]
      end

      # Make sure contact is valid.
      unless @contact && @contact.valid?
        @errors << ['contact', 'is invalid']
      end

      # Make sure all line_items are valid.
      unless line_items.all? { | line_item | line_item.valid? }
        @errors << ['line_items', "at least one line item invalid"]
      end

      @errors.size == 0
    end
913038
public boolean validateAllFields() {
        final boolean postalCodeValid;

        final String countrySelected = mCountryAutoCompleteTextView.getSelectedCountryCode();
        if (mPostalCodeEditText.getText().toString().isEmpty() &&
                (mOptionalShippingInfoFields.contains(POSTAL_CODE_FIELD) ||
                        mHiddenShippingInfoFields.contains(POSTAL_CODE_FIELD))) {
            postalCodeValid = true;
        } else if (countrySelected.equals(Locale.US.getCountry())) {
            postalCodeValid = CountryUtils.isUSZipCodeValid(mPostalCodeEditText.getText()
                    .toString().trim());
        } else if (countrySelected.equals(Locale.UK.getCountry())) {
            postalCodeValid = CountryUtils.isUKPostcodeValid(mPostalCodeEditText.getText()
                    .toString().trim());
        } else if (countrySelected.equals(Locale.CANADA.getCountry())) {
            postalCodeValid = CountryUtils.isCanadianPostalCodeValid(mPostalCodeEditText.getText()
                    .toString().trim());
        } else if (CountryUtils.doesCountryUsePostalCode(countrySelected)) {
            postalCodeValid = !mPostalCodeEditText.getText().toString().isEmpty();
        } else {
            postalCodeValid = true;
        }
        mPostalCodeEditText.setShouldShowError(!postalCodeValid);

        final boolean requiredAddressLine1Empty = mAddressEditText.getText().toString().isEmpty() &&
                !mOptionalShippingInfoFields.contains(ADDRESS_LINE_ONE_FIELD) &&
                !mHiddenShippingInfoFields.contains(ADDRESS_LINE_ONE_FIELD);
        mAddressEditText.setShouldShowError(requiredAddressLine1Empty);

        final boolean requiredCityEmpty = mCityEditText.getText().toString().isEmpty() &&
                !mOptionalShippingInfoFields.contains(CITY_FIELD) && !mHiddenShippingInfoFields
                .contains(CITY_FIELD);
        mCityEditText.setShouldShowError(requiredCityEmpty);

        final boolean requiredNameEmpty = mNameEditText.getText().toString().isEmpty();
        mNameEditText.setShouldShowError(requiredNameEmpty);

        final boolean requiredStateEmpty = mStateEditText.getText().toString().isEmpty() &&
                !mOptionalShippingInfoFields.contains(STATE_FIELD) && !mHiddenShippingInfoFields
                .contains(STATE_FIELD);
        mStateEditText.setShouldShowError(requiredStateEmpty);

        final boolean requiredPhoneNumberEmpty =
                mPhoneNumberEditText.getText().toString().isEmpty() &&
                        !mOptionalShippingInfoFields.contains(PHONE_FIELD) &&
                        !mHiddenShippingInfoFields.contains(PHONE_FIELD);
        mPhoneNumberEditText.setShouldShowError(requiredPhoneNumberEmpty);

        return postalCodeValid && !requiredAddressLine1Empty && !requiredCityEmpty &&
                !requiredStateEmpty && !requiredNameEmpty && !requiredPhoneNumberEmpty;
    }
666927
def _check_values(self, value):
        
        key = self.to_field_name or 'pk'
        # deduplicate given values to avoid creating many querysets or
        # requiring the database backend deduplicate efficiently.
        try:
            value = frozenset(value)
        except TypeError:
            # list of lists isn't hashable, for example
            raise ValidationError(
                self.error_messages['list'],
                code='list',
            )
        for pk in value:
            try:
                self.queryset.filter(**{key: pk})
            except (ValueError, TypeError):
                raise ValidationError(
                    self.error_messages['invalid_pk_value'],
                    code='invalid_pk_value',
                    params={'pk': pk},
                )
        qs = EventOccurrence.objects.filter(**{'%s__in' % key: value})
        pks = set(force_text(getattr(o, key)) for o in qs)
        for val in value:
            if force_text(val) not in pks:
                raise ValidationError(
                    self.error_messages['invalid_choice'],
                    code='invalid_choice',
                    params={'value': val},
                )
        return qs
363693
def is_valid(self, instance):
        

        errors = self.errors(instance)

        if isinstance(errors, list):
            return not any(errors)

        return not bool(errors)
1019106
public Boolean isValid() {

        return addressLine1 != null ||
                addressLine2 != null ||
                city != null ||
                region != null ||
                postalCode != null ||
                (country != null && country != CountryIso.NotSpecified);

    }
837395
def validate(self, value):
        
        errors = []
        value = self._validate_type(value, errors)
        self._validate_value(value, errors)

        if errors:
            raise ValidationErrors(errors)

        return value
907184
def _validate_forbidden(self, forbidden_values, field, value):
        
        if isinstance(value, _str_type):
            if value in forbidden_values:
                self._error(field, errors.FORBIDDEN_VALUE, value)
        elif isinstance(value, Sequence):
            forbidden = set(value) & set(forbidden_values)
            if forbidden:
                self._error(field, errors.FORBIDDEN_VALUES, list(forbidden))
        elif isinstance(value, int):
            if value in forbidden_values:
                self._error(field, errors.FORBIDDEN_VALUE, value)
978540
function valid_errors(errors) {

  /**
   *  Return false if [errors] is empty or if it isn't a non-empty array.
   */

  if (! errors) {
    return false;
  } else {
    if (! (errors instanceof Array)) {
      return false;
    } else {
      if (errors.length === 0) {
        return false;
      }
    }
  }

  return true;

}
318829
def challenge_record_valid?(domain, key)
      record = challenge_record(domain)
      return record && record.data == key
    end
1356194
def validate_public_key(value):
    
    is_valid = False
    exc = None

    for load in (load_pem_public_key, load_ssh_public_key):
        if not is_valid:
            try:
                load(value.encode('utf-8'), default_backend())
                is_valid = True
            except Exception as e:
                exc = e

    if not is_valid:
        raise ValidationError('Public key is invalid: %s' % exc)
800238
def valid?
      @errors = []

      if !contact_id.nil? && contact_id !~ GUID_REGEX
        @errors << ['contact_id', 'must be blank or a valid Xero GUID']
      end

      if status && !CONTACT_STATUS[status]
        @errors << ['status', "must be one of #{CONTACT_STATUS.keys.join('/')}"]
      end

      unless name
        @errors << ['name', "can't be blank"]
      end

      # Make sure all addresses are correct.
      unless addresses.all? { | address | address.valid? }
        @errors << ['addresses', 'at least one address is invalid']
      end

      # Make sure all phone numbers are correct.
      unless phones.all? { | phone | phone.valid? }
        @errors << ['phones', 'at least one phone is invalid']
      end

      @errors.size == 0
    end
61654
def validate_attributes
      unless address.present? || (lat.present? && lng.present?)
        raise ArgumentError, 'Must provide an address, or lat and lng.'
      end

      if address.present? && lat.present? && lng.present?
        raise ArgumentError, 'Cannot provide address, lat and lng.'
      end
    end
758014
def valid?
      valid = true

      rules.each_pair do |field, rules|
        if ! @obj.respond_to?(field)
          raise InvalidKey, "cannot validate non-existent field '#{field}'"
        end

        rules.each do |r|
          if ! r.valid_value?(@obj.send(field))
            valid = false
            errors[field] = {:rule => r.error_key, :params => r.params}
            break
          end
        end
      end

      @valid = valid
    end
229200
def _validate_ipv4(value):
    '''
    
    '''
    if len(value) == 3:
        if not salt.utils.validate.net.ipv4_addr(value[0].strip()):
            return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0])
        if not salt.utils.validate.net.netmask(value[1].strip()):
            return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1])
        if not salt.utils.validate.net.ipv4_addr(value[2].strip()):
            return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2])
    else:
        return False, 'Invalid value: {0} for ipv4 option'.format(value)
    return True, ''
531748
def validate_ip_address(ip_address):
    
    # Validate the IP address
    log = logging.getLogger(mod_logger + '.validate_ip_address')
    if not isinstance(ip_address, basestring):
        log.warn('ip_address argument is not a string')
        return False

    # Ensure there are 3 dots
    num_dots = 0
    for c in ip_address:
        if c == '.':
            num_dots += 1
    if num_dots != 3:
        log.info('Not a valid IP address: {i}'.format(i=ip_address))
        return False

    # Use the socket module to test
    try:
        socket.inet_aton(ip_address)
    except socket.error as e:
        log.info('Not a valid IP address: {i}\n{e}'.format(i=ip_address, e=e))
        return False
    else:
        log.info('Validated IP address: %s', ip_address)
        return True
1149368
def _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway):
    '''
    
    '''
    errors = []
    # Validate DNS configuration
    if dns_proto == 'dhcp':
        if dns_servers is not None:
            errors.append(
                'The dns_servers param cannot be set if unless dns_proto is '
                'set to \'static\''
            )
    else:
        if str(dns_servers).lower() in ['none', '[]']:
            pass
        elif not isinstance(dns_servers, list):
            errors.append(
                'The dns_servers param must be formatted as a list'
            )
        else:
            bad_ips = [x for x in dns_servers
                       if not salt.utils.validate.net.ipv4_addr(x)]
            if bad_ips:
                errors.append('Invalid DNS server IPs: {0}'
                              .format(', '.join(bad_ips)))

    # Validate IP configuration
    if ip_proto == 'dhcp':
        if ip_addrs is not None:
            errors.append(
                'The ip_addrs param cannot be set if unless ip_proto is set '
                'to \'static\''
            )
        if gateway is not None:
            errors.append(
                'A gateway IP cannot be set if unless ip_proto is set to '
                '\'static\''
            )
    else:
        if not ip_addrs:
            errors.append(
                'The ip_addrs param is required to set static IPs'
            )
        elif not isinstance(ip_addrs, list):
            errors.append(
                'The ip_addrs param must be formatted as a list'
            )
        else:
            bad_ips = [x for x in ip_addrs
                       if not salt.utils.validate.net.ipv4_addr(x)]
            if bad_ips:
                errors.append('The following static IPs are invalid: '
                              '{0}'.format(', '.join(bad_ips)))

            # Validate default gateway
            if gateway is not None:
                if not salt.utils.validate.net.ipv4_addr(gateway):
                    errors.append('Gateway IP {0} is invalid'.format(gateway))

    return errors
799689
def is_valid(self):
        
        self._errors = []
        for field in self.fields:
            try:
                field.validate(self)
            except FieldValidationError, e:
                self._errors.extend(e.errors)
        self.validate()
        return not bool(self._errors)