59 lines
1.4 KiB
PHP
Raw Normal View History

<?php
2015-04-27 15:38:34 +12:00
namespace SilverStripe\Forms;
/**
2015-04-27 15:38:34 +12:00
* Text input field with validation for correct email format according to RFC 2822.
*/
2016-11-29 12:31:16 +13:00
class EmailField extends TextField
{
protected $inputType = 'email';
2016-11-29 12:31:16 +13:00
/**
* {@inheritdoc}
*/
public function Type()
{
return 'email text';
}
2016-11-29 12:31:16 +13: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 12:31:16 +13: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 12:31:16 +13:00
// Escape delimiter characters.
$safePattern = str_replace('/', '\\/', $pattern);
2016-11-29 12:31:16 +13:00
if ($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) {
$validator->validationError(
$this->name,
2017-04-20 13:15:24 +12:00
_t('SilverStripe\\Forms\\EmailField.VALIDATION', 'Please enter an email address'),
2016-11-29 12:31:16 +13:00
'validation'
);
2015-04-27 15:38:34 +12:00
2016-11-29 12:31:16 +13:00
return false;
}
2016-11-29 12:31:16 +13:00
return true;
}
2016-10-28 16:22:58 +13:00
2016-11-29 12:31:16 +13:00
public function getSchemaValidation()
{
$rules = parent::getSchemaValidation();
$rules['email'] = true;
return $rules;
}
}