silverstripe-framework/src/Forms/EmailField.php

59 lines
1.2 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.
*/
class EmailField extends TextField {
2015-04-27 05:38:34 +02:00
/**
* {@inheritdoc}
*/
public function Type() {
return 'email text';
}
2015-04-27 05:38:34 +02:00
/**
* {@inheritdoc}
*/
public function getAttributes() {
2012-04-19 04:26:03 +02:00
return array_merge(
parent::getAttributes(),
array(
2015-04-27 05:38:34 +02:00
'type' => 'email',
2012-04-19 04:26:03 +02:00
)
);
}
/**
2015-04-27 05:38:34 +02:00
* Validates for RFC 2822 compliant email addresses.
*
* @see http://www.regular-expressions.info/email.html
* @see http://www.ietf.org/rfc/rfc2822.txt
2015-04-27 05:38:34 +02:00
*
* @param Validator $validator
2015-04-27 05:38:34 +02:00
*
* @return string
*/
public function validate($validator) {
$this->value = trim($this->value);
2015-04-27 05:38:34 +02: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])?$';
2015-04-27 05:38:34 +02:00
// Escape delimiter characters.
$safePattern = str_replace('/', '\\/', $pattern);
2015-04-27 05:38:34 +02:00
if($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) {
2012-04-12 02:17:30 +02:00
$validator->validationError(
$this->name,
2015-04-27 05:38:34 +02:00
_t('EmailField.VALIDATION', 'Please enter an email address'),
'validation'
);
2015-04-27 05:38:34 +02:00
return false;
}
2015-04-27 05:38:34 +02:00
return true;
}
}