silverstripe-framework/src/Forms/EmailField.php

70 lines
1.6 KiB
PHP
Raw Normal View History

<?php
2015-04-27 05:38:34 +02:00
namespace SilverStripe\Forms;
/**
2015-04-27 05:38:34 +02:00
* Text input field with validation for correct email format according to RFC 2822.
*/
2016-11-29 00:31:16 +01:00
class EmailField extends TextField
{
/**
* {@inheritdoc}
*/
public function Type()
{
return 'email text';
}
2016-11-29 00:31:16 +01:00
/**
* {@inheritdoc}
*/
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array(
'type' => 'email',
)
);
}
2016-11-29 00:31:16 +01:00
/**
* Validates for RFC 2822 compliant email addresses.
*
* @see http://www.regular-expressions.info/email.html
* @see http://www.ietf.org/rfc/rfc2822.txt
*
* @param Validator $validator
*
* @return string
*/
public function validate($validator)
{
$this->value = trim($this->value);
2016-11-29 00:31:16 +01:00
$pattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$';
2016-11-29 00:31:16 +01:00
// Escape delimiter characters.
$safePattern = str_replace('/', '\\/', $pattern);
2016-11-29 00:31:16 +01:00
if ($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) {
$validator->validationError(
$this->name,
2017-04-20 03:15:24 +02:00
_t('SilverStripe\\Forms\\EmailField.VALIDATION', 'Please enter an email address'),
2016-11-29 00:31:16 +01:00
'validation'
);
2015-04-27 05:38:34 +02:00
2016-11-29 00:31:16 +01:00
return false;
}
2016-11-29 00:31:16 +01:00
return true;
}
2016-10-28 05:22:58 +02:00
2016-11-29 00:31:16 +01:00
public function getSchemaValidation()
{
$rules = parent::getSchemaValidation();
$rules['email'] = true;
return $rules;
}
}