1 <?php
2 3 4 5 6 7
8 class NumericField extends TextField{
9
10 function __construct($name, $title = null, $value = null, $form = null, $rightTitle = null) {
11 $this->setHTML5Attribute('type', 'number');
12 $this->setHTML5Attribute('step', 'any');
13
14 parent::__construct($name, $title, $value, $form, $rightTitle);
15 }
16
17 function setStep($value) {
18 $this->setHTML5Attribute('step', $value);
19 }
20
21 function setMin($value) {
22 $this->setHTML5Attribute('min', $value);
23 }
24
25 function setMax($value) {
26 $this->setHTML5Attribute('max', $value);
27 }
28
29 function setPattern($value) {
30 $this->setHTML5Attribute('pattern', $value);
31 }
32
33 function Field() {
34 $html = parent::Field();
35 Requirements::javascript(SAPPHIRE_DIR . 'javascript/NumericField.js');
36
37 return $html;
38 }
39
40 function jsValidation() {
41 $formID = $this->form->FormName();
42 $error = _t('NumericField.VALIDATIONJS', 'is not a number, only numbers can be accepted for this field');
43 $jsFunc =<<<JS
44 Behaviour.register({
45 "#$formID": {
46 validateNumericField: function(fieldName) {
47 el = _CURRENT_FORM.elements[fieldName];
48 if(!el || !el.value) return true;
49
50 if(el.value.match(/^\s*(\-?[0-9]+(\.[0-9]+)?\s*$)/)) {
51 return true;
52 } else {
53 validationError(el, "'" + el.value + "' $error","validation");
54 return false;
55 }
56 }
57 }
58 });
59 JS;
60
61 Requirements::customScript($jsFunc, 'func_validateNumericField');
62
63
64 return <<<JS
65 if(typeof fromAnOnBlur != 'undefined'){
66 if(fromAnOnBlur.name == '$this->name')
67 $('$formID').validateNumericField('$this->name');
68 }else{
69 $('$formID').validateNumericField('$this->name');
70 }
71 JS;
72 }
73
74
75 function validate($validator){
76 if($this->value && !is_numeric(trim($this->value))){
77 $validator->validationError(
78 $this->name,
79 sprintf(
80 _t('NumericField.VALIDATION', "'%s' is not a number, only numbers can be accepted for this field"),
81 $this->value
82 ),
83 "validation"
84 );
85 return false;
86 } else{
87 return true;
88 }
89 }
90
91 function dataValue() {
92 return (is_numeric($this->value)) ? $this->value : 0;
93 }
94 }
95 ?>
[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.
-