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

EmailField   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 2

4 Methods

Rating   Name   Duplication   Size   Complexity  
A Type() 0 3 1
A getAttributes() 0 8 1
A validate() 0 20 3
A getSchemaValidation() 0 5 1
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