Blame view

framework/forms/CreditCardField.php 2.35 KB
0084d336   Administrator   Importers CRUD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  <?php
  /**
   * Allows input of credit card numbers via four separate form fields,
   * including generic validation of its numeric values.
   * 
   * @todo Validate
   * 
   * @package forms
   * @subpackage fields-formattedinput
   */
  class CreditCardField extends TextField {
  
  	/**
  	 * Add default attributes for use on all inputs.
  	 *
  	 * @return array List of attributes
  	 */
  	public function getAttributes() {
  		return array_merge(
  			parent::getAttributes(),
  			array(
  				'autocomplete' => 'off',
  				'maxlength' => 4,
  				'size' => 4
  			)
  		);
  	}
  	
  	public function Field($properties = array()) {
  		$parts = $this->value;
  		if(!is_array($parts)) $parts = explode("\n", chunk_split($parts,4,"\n"));
  		$parts = array_pad($parts, 4, "");
  
  		$properties['ValueOne'] = $parts[0];
  		$properties['ValueTwo'] = $parts[1];
  		$properties['ValueThree'] = $parts[2];
  		$properties['ValueFour'] = $parts[3];
  
  		return parent::Field($properties);
  	}
  
  	/**
  	 * Get tabindex HTML string
  	 *
  	 * @param int $increment Increase current tabindex by this value
  	 * @return string
  	 */
  	public function getTabIndexHTML($increment = 0) {
  		// we can't add a tabindex if there hasn't been one set yet.
  		if($this->getAttribute('tabindex') === null) return false;
  
  		$tabIndex = (int)$this->getAttribute('tabindex') + (int)$increment;
  		return (is_numeric($tabIndex)) ? ' tabindex = "' . $tabIndex . '"' : '';
  	}
  
  	public function dataValue() {
  		if(is_array($this->value)) return implode("", $this->value);
  		else return $this->value;
  	}
  	
  	public function validate($validator){
  		// If the field is empty then don't return an invalidation message
  		if(!trim(implode("", $this->value))) return true;
  		
  		$i=0;
  		if($this->value) foreach($this->value as $part){
  			if(!$part || !(strlen($part) == 4) || !preg_match("/([0-9]{4})/", $part)){
  				switch($i){
  					case 0: $number = _t('CreditCardField.FIRST', 'first'); break;
  					case 1: $number = _t('CreditCardField.SECOND', 'second'); break;
  					case 2: $number = _t('CreditCardField.THIRD', 'third'); break;
  					case 3: $number = _t('CreditCardField.FOURTH', 'fourth'); break;
  				}
  				$validator->validationError(
  					$this->name,
  					_t(
  						'Form.VALIDATIONCREDITNUMBER', 
  						"Please ensure you have entered the {number} credit card number correctly",
  						array('number' => $number)
  					),
  					"validation",
  					false
  				);
  				return false;
  			}
  		$i++;
  		}
  	}
  }