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 Field() {
18 $html = parent::Field();
19 Requirements::javascript(SAPPHIRE_DIR . 'javascript/NumericField.js');
20
21 return $html;
22 }
23
24 function jsValidation() {
25 $formID = $this->form->FormName();
26 $error = _t('NumericField.VALIDATIONJS', 'is not a number, only numbers can be accepted for this field');
27 $jsFunc =<<<JS
28 Behaviour.register({
29 "#$formID": {
30 validateNumericField: function(fieldName) {
31 el = _CURRENT_FORM.elements[fieldName];
32 if(!el || !el.value) return true;
33
34 if(el.value.match(/^\s*(\-?[0-9]+(\.[0-9]+)?\s*$)/)) {
35 return true;
36 } else {
37 validationError(el, "'" + el.value + "' $error","validation");
38 return false;
39 }
40 }
41 }
42 });
43 JS;
44
45 Requirements::customScript($jsFunc, 'func_validateNumericField');
46
47
48 return <<<JS
49 if(typeof fromAnOnBlur != 'undefined'){
50 if(fromAnOnBlur.name == '$this->name')
51 $('$formID').validateNumericField('$this->name');
52 }else{
53 $('$formID').validateNumericField('$this->name');
54 }
55 JS;
56 }
57
58
59 function validate($validator){
60 if($this->value && !is_numeric(trim($this->value))){
61 $validator->validationError(
62 $this->name,
63 sprintf(
64 _t('NumericField.VALIDATION', "'%s' is not a number, only numbers can be accepted for this field"),
65 $this->value
66 ),
67 "validation"
68 );
69 return false;
70 } else{
71 return true;
72 }
73 }
74
75 function dataValue() {
76 return (is_numeric($this->value)) ? $this->value : 0;
77 }
78 }
79 ?>
[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.
-