Completed
Push — master ( 4ee78f...ce1053 )
by Damian
14:52 queued 39s
created

EmailField::getSchemaValidation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Forms;
4
5
/**
6
 * Text input field with validation for correct email format according to RFC 2822.
7
 */
8
class EmailField extends TextField {
9
	/**
10
	 * {@inheritdoc}
11
	 */
12
	public function Type() {
13
		return 'email text';
14
	}
15
16
	/**
17
	 * {@inheritdoc}
18
	 */
19
	public function getAttributes() {
20
		return array_merge(
21
			parent::getAttributes(),
22
			array(
23
				'type' => 'email',
24
			)
25
		);
26
	}
27
28
	/**
29
	 * Validates for RFC 2822 compliant email addresses.
30
	 *
31
	 * @see http://www.regular-expressions.info/email.html
32
	 * @see http://www.ietf.org/rfc/rfc2822.txt
33
	 *
34
	 * @param Validator $validator
35
	 *
36
	 * @return string
37
	 */
38
	public function validate($validator) {
39
		$this->value = trim($this->value);
40
41
		$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])?$';
42
43
		// Escape delimiter characters.
44
		$safePattern = str_replace('/', '\\/', $pattern);
45
46
		if($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) {
47
			$validator->validationError(
48
				$this->name,
49
				_t('EmailField.VALIDATION', 'Please enter an email address'),
50
				'validation'
51
			);
52
53
			return false;
54
		}
55
56
		return true;
57
	}
58
59
	public function getSchemaValidation() {
60
		$rules = parent::getSchemaValidation();
61
		$rules['email'] = true;
62
		return $rules;
63
	}
64
}
65