Validate a unix timestamp.

@param mixed $value The value to validate.
@param ValidationField $field The field being validated.
@return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
518352
protected function validateTimestamp($value, ValidationField $field) {
        if (is_numeric($value) && $value > 0) {
            $result = (int)$value;
        } elseif (is_string($value) && $ts = strtotime($value)) {
            $result = $ts;
        } else {
            $field->addTypeError($value, 'timestamp');
            $result = Invalid::value();
        }
        return $result;
    }
25766
public function validateField(Field $field)
    {
        if (false === $this->fieldWasValidated($field)) {
            $this->checkFieldActivation($field);

            if (false === $this->result->fieldIsDeactivated($field)) {
                $this->markFieldAsValidated($field);

                // Looping on the field's validation settings...
                foreach ($field->getValidation() as $validation) {
                    if ($this->result->validationIsDeactivated($validation)) {
                        continue;
                    }

                    $validatorResult = $this->processFieldValidation($field, $validation);

                    // Breaking the loop if an error occurred: we stop the validation process for the current field.
                    if ($validatorResult->hasErrors()) {
                        break;
                    }
                }
            }
        }
    }
399632
protected function validateEnum($value, ValidationField $field) {
        $enum = $field->val('enum');
        if (empty($enum)) {
            return $value;
        }

        if (!in_array($value, $enum, true)) {
            $field->addError(
                'enum',
                [
                    'messageCode' => 'The value must be one of: {enum}.',
                    'enum' => $enum,
                ]
            );
            return Invalid::value();
        }
        return $value;
    }
846714
protected function validateString($value, ValidationField $field) {
        if ($field->val('format') === 'date-time') {
            $result = $this->validateDatetime($value, $field);
            return $result;
        }

        if (is_string($value) || is_numeric($value)) {
            $value = $result = (string)$value;
        } else {
            $field->addTypeError($value, 'string');
            return Invalid::value();
        }

        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
            $field->addError(
                'minLength',
                [
                    'messageCode' => 'The value should be at least {minLength} {minLength,plural,character,characters} long.',
                    'minLength' => $minLength,
                ]
            );
        }
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
            $field->addError(
                'maxLength',
                [
                    'messageCode' => 'The value is {overflow} {overflow,plural,character,characters} too long.',
                    'maxLength' => $maxLength,
                    'overflow' => mb_strlen($value) - $maxLength,
                ]
            );
        }
        if ($pattern = $field->val('pattern')) {
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';

            if (!preg_match($regex, $value)) {
                $field->addError(
                    'pattern',
                    [
                        'messageCode' => $field->val('x-patternMessageCode', 'The value doesn\'t match the required pattern {pattern}.'),
                        'pattern' => $regex,
                    ]
                );
            }
        }
        if ($format = $field->val('format')) {
            $type = $format;
            switch ($format) {
                case 'date':
                    $result = $this->validateDatetime($result, $field);
                    if ($result instanceof \DateTimeInterface) {
                        $result = $result->format("Y-m-d\T00:00:00P");
                    }
                    break;
                case 'email':
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
                    break;
                case 'ipv4':
                    $type = 'IPv4 address';
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
                    break;
                case 'ipv6':
                    $type = 'IPv6 address';
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
                    break;
                case 'ip':
                    $type = 'IP address';
                    $result = filter_var($result, FILTER_VALIDATE_IP);
                    break;
                case 'uri':
                    $type = 'URL';
                    $result = filter_var($result, FILTER_VALIDATE_URL);
                    break;
                default:
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
            }
            if ($result === false) {
                $field->addError('format', [
                    'format' => $format,
                    'formatCode' => $type,
                    'value' => $value,
                    'messageCode' => '{value} is not a valid {formatCode}.'
                ]);
            }
        }

        if ($field->isValid()) {
            return $result;
        } else {
            return Invalid::value();
        }
    }
167303
static public function timestamp($value)
    {
        $value || $value = time();
        if(is_numeric($value)) {
            //$value = strftime('%Y-%m-%d %H:%M:%S', $value);
            $value = strftime('%Y-%m-%d %H:%M:%S', $value);
        }
        
        return $value;
    }
1060797
private function resolveTimeValue($value)
    {
        if (is_int($value)) {
            return $value;
        }

        $timestamp = strtotime($value);

        if (false === $timestamp) {
            throw new InvalidArgumentException(
                "'{$value}' is invalid time string"
            );
        }

        return $timestamp;
    }
38904
protected function confirmValidate($value, $field)
    {
        return isset($this->data[$field]) && $this->data[$field] === $value;
    }
1060299
protected function validateBetween($field, $value, $params)
    {
        if (!\is_numeric($value)) {
            return false;
        }
        if (!isset($params[0]) || !\is_array($params[0]) || \count($params[0]) !== 2) {
            return false;
        }

        list($min, $max) = $params[0];

        return $this->validateMin($field, $value, [$min]) && $this->validateMax($field, $value, [$max]);
    }
1322676
private function callValidators($value, ValidationField $field) {
        $valid = true;

        // Strip array references in the name except for the last one.
        $key = $field->getSchemaPath();
        if (!empty($this->validators[$key])) {
            foreach ($this->validators[$key] as $validator) {
                $r = call_user_func($validator, $value, $field);

                if ($r === false || Invalid::isInvalid($r)) {
                    $valid = false;
                }
            }
        }

        // Add an error on the field if the validator hasn't done so.
        if (!$valid && $field->isValid()) {
            $field->addError('invalid', ['messageCode' => 'The value is invalid.']);
        }
    }
142553
protected function validate($value){
        if( parent::validate($value) ){
            if( $this->required && empty($value) ){
                throw new ValidateException(sprintf($this->__('Field %s is required.'), $this->label));
            }
            return true;
        }else{
            return false;
        }
    }
522133
public function isValid($value)
    {
        $valueString = (string) $value;

        $this->_setValue($valueString);

        if (!preg_match('/^\d{2}:\d{2}$/', $valueString)) {
            $this->_error(self::NOT_HH_MM);
            return false;
        }

        list($hour, $minute) = sscanf($valueString, '%d:%d');
        
        if ($hour > 23 || $minute > 59) {
            $this->_error(self::INVALID);
            return false;
        }

        return true;
    }
209191
public static function validate($value, array $field)
    {
        if (!isset($field['type'])) {
            $field['type'] = 'text';
        }
        $type = $validate['type'] ?? $field['type'];
        $validate = (array)($field['validate'] ?? null);
        $required = $validate['required'] ?? false;

        // If value isn't required, we will stop validation if empty value is given.
        if ($required !== true && ($value === null || $value === '' || (($field['type'] === 'checkbox' || $field['type'] === 'switch') && $value == false))
        ) {
            return [];
        }

        // Get language class.
        $language = Grav::instance()['language'];

        $name = ucfirst($field['label'] ?? $field['name']);
        $message = (string) isset($field['validate']['message'])
            ? $language->translate($field['validate']['message'])
            : $language->translate('GRAV.FORM.INVALID_INPUT', null, true) . ' "' . $language->translate($name) . '"';


        // Validate type with fallback type text.
        $method = 'type' . str_replace('-', '_', $type);

        // If this is a YAML field validate/filter as such
        if (isset($field['yaml']) && $field['yaml'] === true) {
            $method = 'typeYaml';
        }

        $messages = [];

        $success = method_exists(__CLASS__, $method) ? self::$method($value, $validate, $field) : true;
        if (!$success) {
            $messages[$field['name']][] = $message;
        }

        // Check individual rules.
        foreach ($validate as $rule => $params) {
            $method = 'validate' . ucfirst(str_replace('-', '_', $rule));

            if (method_exists(__CLASS__, $method)) {
                $success = self::$method($value, $params);

                if (!$success) {
                    $messages[$field['name']][] = $message;
                }
            }
        }

        return $messages;
    }
1042268
protected function _setFieldValue($field, $value)
    {
        // ignore setting versioning fields
        if (static::isVersioned()) {
            if (array_key_exists($field, static::$versioningFields)) {
                return false;
            }
        }

        if (!static::fieldExists($field)) {
            return false;
        }
        $fieldOptions = static::$_classFields[get_called_class()][$field];

        // no overriding autoincrements
        if ($fieldOptions['autoincrement']) {
            return false;
        }

        // pre-process value
        $forceDirty = false;
        switch ($fieldOptions['type']) {
            case 'clob':
            case 'string':
            {
                $value = $this->_setStringValue($fieldOptions, $value);
                break;
            }

            case 'boolean':
            {
                $value = $this->_setBooleanValue($value);
                break;
            }

            case 'decimal':
            {
                $value = $this->_setDecimalValue($value);
                break;
            }

            case 'int':
            case 'uint':
            case 'integer':
            {
                $value = $this->_setIntegerValue($fieldOptions, $value);
                break;
            }

            case 'timestamp':
            {
                $value = $this->_setTimestampValue($value);
                break;
            }

            case 'date':
            {
                $value = $this->_setDateValue($value);
                break;
            }

            // these types are converted to strings from another PHP type on save
            case 'serialized':
            {
                $this->_convertedValues[$field] = $value;
                $value = $this->_setSerializedValue($value);
                break;
            }
            case 'enum':
            {
                $value = $this->_setEnumValue($fieldOptions, $value);
                break;
            }
            case 'set':
            case 'list':
            {
                $value = $this->_setListValue($fieldOptions, $value);
                $this->_convertedValues[$field] = $value;
                $forceDirty = true;
                break;
            }
        }

        if ($forceDirty || (empty($this->_record[$field]) && isset($value)) || ($this->_record[$field] !== $value)) {
            $columnName = static::_cn($field);
            if (isset($this->_record[$columnName])) {
                $this->_originalValues[$field] = $this->_record[$columnName];
            }
            $this->_record[$columnName] = $value;
            $this->_isDirty = true;

            // unset invalidated relationships
            if (!empty($fieldOptions['relationships']) && static::isRelational()) {
                foreach ($fieldOptions['relationships'] as $relationship => $isCached) {
                    if ($isCached) {
                        unset($this->_relatedObjects[$relationship]);
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }
1133050
protected function validateDate($attribute, $value)
    {
        if ($value instanceof DateTime) {
            return true;
        }

        if (strtotime($value) === false) {
            return false;
        }

        $date = date_parse($value);

        return checkdate($date['month'], $date['day'], $date['year']);
    }
1009372
protected void validateField(int field) {
        int y;
        switch (field) {
        case DAY_OF_MONTH:
            y = handleGetExtendedYear();
            validateField(field, 1, handleGetMonthLength(y, internalGet(MONTH)));
            break;
        case DAY_OF_YEAR:
            y = handleGetExtendedYear();
            validateField(field, 1, handleGetYearLength(y));
            break;
        case DAY_OF_WEEK_IN_MONTH:
            if (internalGet(field) == 0) {
                throw new IllegalArgumentException("DAY_OF_WEEK_IN_MONTH cannot be zero");
            }
            validateField(field, getMinimum(field), getMaximum(field));
            break;
        default:
            validateField(field, getMinimum(field), getMaximum(field));
            break;
        }
    }
807326
public function validate($validator)
    {
        // Don't validate empty fields
        if (empty($this->rawValue)) {
            return true;
        }

        // We submitted a value, but it couldn't be parsed
        if (empty($this->value)) {
            $validator->validationError(
                $this->name,
                _t(
                    'SilverStripe\\Forms\\TimeField.VALIDATEFORMAT',
                    "Please enter a valid time format ({format})",
                    ['format' => $this->getTimeFormat()]
                )
            );
            return false;
        }
        return true;
    }
942097
protected function validateField( $field, $value )
    {
        switch ( $field )
        {
            case 'website':
                return ezcomUtility::validateURLString( $value );
            case 'email':
                // just validate anonymous's input email
                $user = eZUser::currentUser();
                if( $user->isAnonymous() )
                {
                    $result = eZMail::validate( $value );
                    if ( !$result )
                    {
                        return ezpI18n::tr( 'ezcomments/comment/add', 'Not a valid email address.' );
                    }
                }
                return true;
            case 'recaptcha':
                require_once 'recaptchalib.php';
                $ini = eZINI::instance( 'ezcomments.ini' );
                $privateKey = $ini->variable( 'RecaptchaSetting' , 'PrivateKey' );
                $http = eZHTTPTool::instance();
                if( $http->hasPostVariable( 'recaptcha_challenge_field' ) &&
                    $http->hasPostVariable( 'recaptcha_response_field' ) )
                {
                    $ip = $_SERVER["REMOTE_ADDR"];
                    $challengeField = $http->postVariable( 'recaptcha_challenge_field' );
                    $responseField = $http->postVariable( 'recaptcha_response_field' );
                    $capchaResponse = recaptcha_check_answer( $privateKey, $ip, $challengeField, $responseField );
                    if( !$capchaResponse->is_valid )
                    {
                         return ezpI18n::tr( 'ezcomments/comment/add', 'The words you input are incorrect.' );
                    }
                }
                else
                {
                    return ezpI18n::tr( 'ezcomments/comment/add', 'Captcha parameter error.' );
                }
                return true;
            default:
                return true;
        }
    }