Checks every phone number in table to verify that it meets phone criteria, then calls format_phone method to wrap Valid results.  Otherwise destroys Invalid phone fields and associations.
 Call: Wrap.new.validate_phone(phone)
184091
def validate_phone(phone)
      phone_hsh = { phone_status: nil, phone: phone, phone_f: nil }
      return phone_hsh unless phone.present?
      phone = phone&.gsub(/\s/, ' ')&.strip
      reg = Regexp.new('[(]?[0-9]{3}[ ]?[)-.]?[ ]?[0-9]{3}[ ]?[-. ][ ]?[0-9]{4}')
      phone = nil if phone.first == '0' || phone.include?('(0') || !reg.match(phone)
      phone_hsh[:phone_f] = format_phone(phone) if phone.present?
      phone_hsh = check_phone_status(phone_hsh)
      phone_hsh
    end
1276085
def phone_search_query(self, **kwargs):
        
        if not kwargs.get('phone'):
            raise ValueError('A valid phone number (parameter "phone") must be provided.')

        return self._query(PHONE_SEARCH_API_URL, **kwargs)
1345543
def check_phone_status(hsh)
      phone = hsh[:phone]
      phone_f = hsh[:phone_f]
      status = 'invalid'
      status = phone != phone_f ? 'formatted' : 'unchanged' if phone && phone_f
      hsh[:phone_status] = status if status.present?
      hsh
    end
1087856
def phonenumber_validation(data):
    
    from phonenumber_field.phonenumber import to_python
    phone_number = to_python(data)
    if not phone_number:
        return data
    elif not phone_number.country_code:
        raise serializers.ValidationError(_("Phone number needs to include valid country code (E.g +37255555555)."))
    elif not phone_number.is_valid():
        raise serializers.ValidationError(_('The phone number entered is not valid.'))

    return data
472161
def _validate_data(self, data: dict):
        
        log.debug("validating provided data")
        e = best_match(self.validator.iter_errors(data))
        if e:
            custom_error_key = f"error_{e.validator}"
            msg = (
                e.schema[custom_error_key]
                if e.schema.get(custom_error_key)
                else e.message
            )
            raise BadArguments(validation_error=msg, provider=self.name, data=data)
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
143105
def validate(self):
        
        validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt
        validation_scope = {}
        exec(validation_code, validation_scope)
        # Store the result in the first function in the group.
        if len(self.groups[self.group]) == 1:
            self.result = validation_scope['validation_result']
            logging.info('PyPerform: Validating group "{b.group}" against function "{b.callable.__name__}"'
                         .format(b=self))
        else:
            compare_against_benchmark = self.groups[self.group][0]
            test = [benchmark.result_validation for benchmark in self.groups[self.group]]
            if not all(test):
                raise ValueError('All functions within a group must have the same validation flag.')
            compare_result = compare_against_benchmark.result
            if self.validation_func:
                results_are_valid = self.validation_func(compare_result, validation_scope['validation_result'])
            else:
                results_are_valid = compare_result == validation_scope['validation_result']
            if results_are_valid:
                logging.info('PyPerform: Validating {}......PASSED!'.format(self.callable.__name__))
            else:
                error = 'Results of functions {0} and {1} are not equivalent.\n{0}:\t {2}\n{1}:\t{3}'
                raise ValidationError(error.format(compare_against_benchmark.callable.__name__, self.callable.__name__,
                                          compare_result, validation_scope['validation_result']))
78617
def phone_number=(phone_number)

      if !phone_number.nil? && phone_number.to_s.length > 16
        fail ArgumentError, "invalid value for 'phone_number', the character length must be smaller than or equal to 16."
      end

      @phone_number = phone_number
    end
1335981
def run_validation(field_name, options)
      promise = Promise.new.resolve(nil)
      options.each_pair do |validation, args|
        # Call the specific validator, then merge the results back
        # into one large errors hash.
        klass = validation_class(validation, args)

        if klass
          # Chain on the promises
          promise = promise.then do
            klass.validate(self, field_name, args)
          end.then do |errs|
            errors.merge!(errs)
          end
        else
          fail "validation type #{validation} is not specified."
        end
      end

      promise
    end
1356463
def validate
      errors = {}

      call_validators do |name, message|
        errors[name] ||= []
        errors[name] << to_error(message)
      end

      errors
    end
273284
def valid(number):
    
    checksum = 0

    number_len = len(number)
    offset = ord('0')

    i = number_len - 1
    while i >= 0:
      n = ord(number[i]) - offset
      checksum += n
      i -= 2

    i = number_len - 2
    while i >= 0:
      n = ord(number[i]) - offset
      n *= 2
      if n > 9:
          n -= 9
      checksum += n
      i -= 2

    return checksum%10 == 0
977946
def is_valid(self, model, validator=None):
    
    if self.property_name and self.is_property_specific:
      arg0 = getattr(model, self.property_name)
    else:
      arg0 = model

    if self.is_simple:
      is_valid = self.callback(arg0)
    else:
      is_valid = self.callback(arg0, validator)

    return (is_valid, None if is_valid else (self.message or "is invalid"))
600072
def validate(self, raw_data, **kwargs):
        
        super(BooleanField, self).validate(raw_data, **kwargs)
        if isinstance(raw_data, string_types):
            valid_data = raw_data.strip().lower() == 'true'
        elif isinstance(raw_data, bool):
            valid_data = raw_data
        else:
            valid_data = raw_data > 0
        return valid_data
1284431
public function isValid($my_number = '')
    {
        try {
            $phoneNumber = new PhoneNumber();
            $phoneNumber->setDebugStatus($this->DEBUG);
            $phoneNumber->setLoggerPath($this->loggerPath);
            $phoneNumber->__construct();
            $result = $phoneNumber->is_valid(trim($my_number), self::CURRENT_COUNTRY);
            $this->_debug->info(__FUNCTION__, 'Result: ' . $result);

            return $result;
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            if (function_exists('log_message')) {
                log_message('error', $message);
            }
            $this->_debug->error(__FUNCTION__, $message);

            return NULL;
        }
    }
1017460
def format_phone(phone)
      regex = Regexp.new('[A-Z]+[a-z]+')
      if !phone.blank? && (phone != 'N/A' || phone != '0') && !regex.match(phone)
        phone_stripped = phone.gsub(/[^0-9]/, '')
        phone_step2 = phone_stripped && phone_stripped[0] == '1' ? phone_stripped[1..-1] : phone_stripped
        final_phone = !(phone_step2 && phone_step2.length < 10) ? "(#{phone_step2[0..2]}) #{(phone_step2[3..5])}-#{(phone_step2[6..9])}" : phone
      else
        final_phone = nil
      end
      final_phone
    end
592260
def _validate(self):
        
        if self.data_format is FormatType.PYTHON:
            self.data = self.raw_data
        elif self.data_format is FormatType.JSON:
            self._validate_json()
        elif self.data_format is FormatType.YAML:
            self._validate_yaml()
388591
public function validate()
    {
        $v = $this->validator();

        /**
         * Validation map
         *
         * Format:
         *
         * 'key' =>  array(
         *    'method' => this class method name to call, string, required
         *    'method_args' => optional args for 'method' call, array, optional
         *    'v_method' => validator method to call, string, required
         *    'error' => custom error string when validation fails, optional
         *               if not set, error string fprmatted as "Invalid '$key' specified"
         *    'v_error_method' => validator method - when called returned error string
         *                        prepared by validator, optional,
         *                        if not set => see 'error'
         *    'optional' => optional value, if it's empty validation result ignored
         *
         */
        $validateMap = array(
            'name' => array('method' => 'getName',
                'v_method' => 'validatePackageName',
                'error'=>"Invalid package name, allowed: [a-zA-Z0-9_-] chars"),
            'version' => array('method' => 'getVersion',
                'v_method' => 'validateVersion',
                'error'=>"Invalid version, should be like: x.x.x"),
            'stability' => array('method' => 'getStability',
                'v_method' => 'validateStability',
                'error'=>"Invalid stability"),
            'date' => array('method' => 'getDate',
                'v_method' => 'validateDate',
                'error'=>"Invalid date, should be YYYY-DD-MM"),
            'license_uri' => array('method' => 'getLicenseUri',
                'v_method' => 'validateLicenseUrl',
                'error'=>"Invalid license URL"),
            'channel' => array('method' => 'getChannel',
                'v_method' => 'validateChannelNameOrUri',
                'error'=>"Invalid channel URL"),
            'authors' => array('method' => 'getAuthors',
                'v_method' => 'validateAuthors',
                'v_error_method' => 'getErrors'),
            'php_min' => array('method' => 'getDependencyPhpVersionMin',
                'v_method' => 'validateVersion',
                'error' => 'PHP minimum version invalid',
                'optional' => true ),
            'php_max' => array('method' => 'getDependencyPhpVersionMax',
                'v_method' => 'validateVersion',
                'error' => 'PHP maximum version invalid',
                'optional' => true ),
            'compatible' => array('method' => 'getCompatible',
                'v_method' => 'validateCompatible',
                'v_error_method' => 'getErrors'),
            'content' => array('method' => 'getContents',
                'v_method' => 'validateContents',
                'v_args' => array('config' => $this->getConfig()),
                'v_error_method' => 'getErrors'),
        );

        $errors = array();
        /**
         * Iterate validation map
         */
        foreach($validateMap as $name=>$data) {

            /**
             * Check mandatory rules fields
             */
            if(!isset($data['method'], $data['v_method'])) {
                throw new Mage_Exception("Invalid rules specified!");
            }

            $method = $data['method'];
            $validatorMethod = $data['v_method'];

            /**
             * If $optional === false, value is mandatory
             */
            $optional = isset($data['optional']) ? (bool) $data['optional'] : false;

            /**
             * Check for method availability, package
             */
            if(!method_exists($this, $method)) {
                throw new Mage_Exception("Invalid method specified for Package : $method");
            }

            /**
             * Check for method availability, validator
             */
            if(!method_exists($v, $validatorMethod)) {
                throw new Mage_Exception("Invalid method specified for Validator : $validatorMethod");
            }

            /**
             * If    $data['error'] => get error string from $data['error']
             * Else  concatenate "Invalid '{$name}' specified"
             */
            $errorString = isset($data['error']) ? $data['error'] : "Invalid '{$name}' specified";

            /**
             * Additional method args check
             * array() by default
             */
            $methodArgs = isset($data['method_args']) ? $data['method_args'] : array();

            /**
             * Call package method
             */
            $out = @call_user_func_array(array($this, $method), $methodArgs);

            /**
             * Skip if result is empty and value is optional
             */
            if(empty($out) && $optional) {
                continue;
            }

            /**
             * Additional validator arguments, merged with array($out)
             */
            $validatorArgs = isset($data['v_args']) ? array_merge(array($out), $data['v_args']) : array($out);

            /**
             * Get validation result
             */
            $result = call_user_func_array(array($v, $validatorMethod), $validatorArgs);

            /**
             * Skip if validation success
             */
            if($result) {
                continue;
            }

            /**
             * From where to get error string?
             * If    validator callback method specified, call it to get errors array
             * Else  get it from $errorString - local error string
             */
            $validatorFetchErrorsMethod = isset($data['v_error_method']) ? $data['v_error_method'] : false;
            if (false !== $validatorFetchErrorsMethod) {
                $errorString = call_user_func_array(array($v, $validatorFetchErrorsMethod), array());
            }

            /**
             * If   errors is array => merge
             * Else append
             */
            if(is_array($errorString)) {
                $errors = array_merge($errors, $errorString);
            } else {
                $errors[] = $errorString;
            }
        }
        /**
         * Set local errors
         */
        $this->setErrors($errors);
        /**
         * Return true if there's no errors :)
         */
        return ! $this->hasErrors();
    }