1 <?php
2 3 4 5 6
7 class EmailField extends TextField {
8
9 function __construct($name, $title = null, $value = null, $form = null, $rightTitle = null) {
10 $this->setHTML5Attribute('type', 'email');
11 $this->setAutocomplete('email');
12
13 parent::__construct($name, $title, $value, $form, $rightTitle);
14 }
15
16 function jsValidation() {
17 $formID = $this->form->FormName();
18 $error = _t('EmailField.VALIDATIONJS', 'Please enter an email address.');
19 $jsFunc =<<<JS
20 Behaviour.register({
21 "#$formID": {
22 validateEmailField: function(fieldName) {
23 var el = _CURRENT_FORM.elements[fieldName];
24 if(!el || !el.value) return true;
25
26 if(el.value.match(/^([a-zA-Z0-9_+\.\x27-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)) {
27 return true;
28 } else {
29 validationError(el, "$error","validation");
30 return false;
31 }
32 }
33 }
34 });
35 JS;
36
37 Requirements::customScript($jsFunc, 'func_validateEmailField' .'_' . $formID);
38
39
40 return <<<JS
41 if(typeof fromAnOnBlur != 'undefined'){
42 if(fromAnOnBlur.name == '$this->name')
43 $('$formID').validateEmailField('$this->name');
44 }else{
45 $('$formID').validateEmailField('$this->name');
46 }
47 JS;
48 }
49
50 function validate($validator){
51 $this->value = trim($this->value);
52 if($this->value && !ereg('^([a-zA-Z0-9_+\'.-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$', $this->value)){
53 $validator->validationError(
54 $this->name,
55 _t('EmailField.VALIDATION', "Please enter an email address."),
56 "validation"
57 );
58 return false;
59 } else{
60 return true;
61 }
62 }
63 }
64 ?>
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the
Silverstripe Forums to ask development related questions.
-