summaryrefslogtreecommitdiff
path: root/framework/Web/UI/WebControls/TBaseValidator.php
blob: ff026b4924cae26fc4842adf492b5ad8c633e2f5 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<?php
/**
 * TBaseValidator class file
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Revision: $  $Date: $
 * @package System.Web.UI.WebControls
 */

/**
 * Using TLabel class
 */
Prado::using('System.Web.UI.WebControls.TLabel');

/**
 * TBaseValidator class
 *
 * TBaseValidator serves as the base class for validator controls.
 *
 * Validation is performed when a postback control, such as a TButton, a TLinkButton
 * or a TTextBox (under AutoPostBack mode) is submitting the page and
 * its <b>CausesValidation</b> property is true.
 * You can also manually perform validation by calling {@link TPage::validate()}.
 * The input control to be validated is specified by {@link setControlToValidate ControlToValidate}.
 *
 * Validator controls always validate the associated input control on the serve side.
 * In addition, if {@link getEnableClientScript EnableClientScript} is true,
 * validation will also be performed on the client-side using javascript.
 * Client-side validation will validate user input before it is sent to the server.
 * The form data will not be submitted if any error is detected. This avoids
 * the round-trip of information necessary for server-side validation.
 *
 * You can use multiple validator controls to validate a single input control,
 * each responsible for validating against a different criteria.
 * For example, on a user registration form, you may want to make sure the user
 * enters a value in the username text box, and the input must consist of only word
 * characters. You can use a {@link TRequiredFieldValidator} to ensure the input
 * of username and a {@link TRegularExpressionValidator} to ensure the proper input.
 *
 * If an input control fails validation, the text specified by the {@link setErrorMessage ErrorMessage}
 * property is displayed in the validation control. However, if the {@link setText Text}
 * property is set, it will be displayed instead. If both {@link setErrorMessage ErrorMessage}
 * and {@link setText Text} are empty, the body content of the validator will
 * be displayed. Error display is controlled by {@link setDisplay Display} property.
 *
 * You can also customized the client-side behaviour by adding javascript
 * code to the subproperties of the {@link getClientSide ClientSide}
 * property. See quickstart documentation for further details.
 *
 * You can also place a {@link TValidationSummary} control on a page to display error messages
 * from the validators together. In this case, only the {@link setErrorMessage ErrorMessage}
 * property of the validators will be displayed in the {@link TValidationSummary} control.
 *
 * Validators can be partitioned into validation groups by setting their
 * {@link setValidationGroup ValidationGroup} property. If the control causing the
 * validation also sets its ValidationGroup property, only those validators having
 * the same ValidationGroup value will do input validation.
 *
 * Note, the {@link TPage::getIsValid IsValid} property of the current {@link TPage}
 * instance will be automatically updated by the validation process which occurs
 * after {@link TPage::onLoad onLoad} of {@link TPage} and before the postback events.
 * Therefore, if you use the {@link TPage::getIsValid()} property in
 * the {@link TPage::onLoad()} method, you must first explicitly call
 * the {@link TPage::validate()} method.
 *
 * <b>Notes to Inheritors</b>  When you inherit from TBaseValidator, you must
 * override the method {@link evaluateIsValid}.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Revision: $  $Date: $
 * @package System.Web.UI.WebControls
 * @since 3.0
 */
abstract class TBaseValidator extends TLabel implements IValidator
{
	/**
	 * @var boolean whether the validation succeeds
	 */
	private $_isValid=true;
	/**
	 * @var boolean whether the validator has been registered with the page
	 */
	private $_registered=false;
	/**
	 * @var TClientSideValidatorOptions validator client-script options.
	 */
	private $_clientSide;
	/**
	 * Controls for which the client-side validation3.js file needs to handle
	 * them specially.
	 * @var array list of control class names
	 */
	private static $_clientClass = array('THtmlArea', 'TDatePicker');

	/**
	 * Constructor.
	 * This method sets the foreground color to red.
	 */
	public function __construct()
	{
		parent::__construct();
		$this->setForeColor('red');
	}

	/**
	 * Registers the validator with page.
	 * @param mixed event parameter
	 */
	public function onInit($param)
	{
		parent::onInit($param);
		$this->getPage()->getValidators()->add($this);
		$this->_registered=true;
	}

	/**
	 * Unregisters the validator from page.
	 * @param mixed event parameter
	 */
	public function onUnload($param)
	{
		if($this->_registered && ($page=$this->getPage())!==null)
			$page->getValidators()->remove($this);
		$this->_registered=false;
		parent::onUnload($param);
	}

	/**
	 * Adds attributes to renderer. Calls parent implementation and renders the
	 * client control scripts.
	 * @param THtmlWriter the renderer
	 */
	protected function addAttributesToRender($writer)
	{
		$display=$this->getDisplay();
		$visible=$this->getEnabled(true) && !$this->getIsValid();
		if($display==='None' || (!$visible && $display==='Dynamic'))
			$writer->addStyleAttribute('display','none');
		else if(!$visible)
			$writer->addStyleAttribute('visibility','hidden');
		$writer->addAttribute('id',$this->getClientID());
		parent::addAttributesToRender($writer);
		$this->renderClientControlScript($writer);
	}

	/**
	 * Returns an array of javascript validator options.
	 * @return array javascript validator options.
	 */
	protected function getClientScriptOptions()
	{
		$control = $this->getValidationTarget();
		$options['ID'] = $this->getClientID();
		$options['FormID'] = $this->getPage()->getForm()->getClientID();
		$options['Display'] = $this->getDisplay();
		$options['ErrorMessage'] = $this->getErrorMessage();
		if($this->getFocusOnError())
		{
			$options['FocusOnError'] = $this->getFocusOnError();
			$options['FocusElementID'] = $this->getFocusElementID();
		}
		$options['ValidationGroup'] = $this->getValidationGroup();
		$options['ControlToValidate'] = $control->getClientID();
		$options['ControlCssClass'] = $this->getControlCssClass();

		$options['ControlType'] = $this->getClientControlClass($control);
		
		//get date format from date picker target control
		if($control instanceof TDatePicker)
			$options['DateFormat'] = $control->getDateFormat();

		if(!is_null($this->_clientSide))
			$options = array_merge($options,$this->_clientSide->getOptions()->toArray());

		return $options;
	}

	/**
	 * Gets the Control type for client-side validation. If new cases exists in
	 * TBaseValidator::$_clientClass, be sure to update the corresponding
	 * "Javascript/validation3.js" file as well.
	 * @param TControl control to validate.
	 * @return string control type for client-side validation.
	 */
	private function getClientControlClass($control)
	{
		foreach(self::$_clientClass as $type)
			if($control instanceof $type)
				return $type;
		return get_class($control);
	}

	/**
	 * Gets the TClientSideValidatorOptions that allows modification of the client-
	 * side validator events.
	 *
	 * The client-side validator supports the following events.
	 * # <tt>OnValidate</tt> -- raised before client-side validation is
	 * executed.
	 * # <tt>OnSuccess</tt> -- raised after client-side validation is completed
	 * and is successfull, overrides default validator error messages updates.
	 * # <tt>OnError</tt> -- raised after client-side validation is completed
	 * and failed, overrides default validator error message updates.
	 *
	 * You can attach custom javascript code to each of these events
	 *
	 * @return TClientSideValidatorOptions javascript validator event options.
	 */
	public function getClientSide()
	{
		if(is_null($this->_clientSide))
			$this->_clientSide = $this->createClientSideOptions();
		return $this->_clientSide;
	}

	/**
	 * @return TClientSideValidatorOptions javascript validator event options.
	 */
	protected function createClientSideOptions()
	{
		return new TClientSideValidatorOptions;
	}

	/**
	 * Renders the javascript code to the end script.
	 * If you override this method, be sure to call the parent implementation
	 * so that the event handlers can be invoked.
	 * @param THtmlWriter the renderer
	 */
	public function renderClientControlScript($writer)
	{
		$scripts = $this->getPage()->getClientScript();
		$formID=$this->getPage()->getForm()->getClientID();
		$scriptKey = "TBaseValidator:$formID";
		if($this->getEnableClientScript() && !$scripts->isEndScriptRegistered($scriptKey))
		{
			$manager['FormID'] = $formID;
			$options = TJavaScript::encode($manager);
			$scripts->registerPradoScript('validator');
			$scripts->registerEndScript($scriptKey, "new Prado.ValidationManager({$options});");
		}
		if($this->getEnableClientScript())
			$this->registerClientScriptValidator();
		$this->updateControlCssClass();
	}

	/**
	 * Update the ControlToValidate component's css class depending
	 * if the ControlCssClass property is set, and whether this is valid.
	 * @return boolean true if change, false otherwise.
	 */
	protected function updateControlCssClass()
	{
		if(($cssClass=$this->getControlCssClass())!=='')
		{
			$control=$this->getValidationTarget();
			if($control instanceof TWebControl)
			{
				$class = preg_replace ('/ '.preg_quote($cssClass).'/', '',$control->getCssClass());
				if(!$this->getIsValid())
					$class .= ' '.$cssClass;
				$control->setCssClass($class);
			}
		}
	}

	/**
	 * Registers the individual validator client-side javascript code.
	 */
	protected function registerClientScriptValidator()
	{
		if($this->getEnabled(true))
		{
			$key = 'prado:'.$this->getClientID();
			$options = TJavaScript::encode($this->getClientScriptOptions());
			$script = 'new '.$this->getClientClassName().'('.$options.');';
			$this->getPage()->getClientScript()->registerEndScript($key, $script);
		}
	}

	/**
	 * Gets the name of the javascript class responsible for performing validation for this control.
	 * This method overrides the parent implementation.
	 * @return string the javascript class name
	 */
	abstract protected function getClientClassName();

	/**
	 * This method overrides the parent implementation to forbid setting ForControl.
	 * @param string the associated control ID
	 * @throws TNotSupportedException whenever this method is called
	 */
	public function setForControl($value)
	{
		throw new TNotSupportedException('basevalidator_forcontrol_unsupported',get_class($this));
	}

	/**
	 * This method overrides parent's implementation by setting {@link setIsValid IsValid} to true if disabled.
	 * @param boolean whether the validator is enabled.
	 */
	public function setEnabled($value)
	{
		$value=TPropertyValue::ensureBoolean($value);
		parent::setEnabled($value);
		if(!$value)
			$this->_isValid=true;
	}

	/**
	 * @return string the display behavior (None, Static, Dynamic) of the error message in a validation control. Defaults to Static.
	 */
	public function getDisplay()
	{
		return $this->getViewState('Display','Static');
	}

	/**
	 * Sets the display behavior (None, Static, Dynamic) of the error message in a validation control.
	 * @param string the display behavior (None, Static, Dynamic)
	 */
	public function setDisplay($value)
	{
		$this->setViewState('Display',TPropertyValue::ensureEnum($value,array('None','Static','Dynamic')),'Static');
	}

	/**
	 * @return boolean whether client-side validation is enabled.
	 */
	public function getEnableClientScript()
	{
		return $this->getViewState('EnableClientScript',true);
	}

	/**
	 * @param boolean whether client-side validation is enabled.
	 */
	public function setEnableClientScript($value)
	{
		$this->setViewState('EnableClientScript',TPropertyValue::ensureBoolean($value),true);
	}

	/**
	 * @return string the text for the error message.
	 */
	public function getErrorMessage()
	{
		return $this->getViewState('ErrorMessage','');
	}

	/**
	 * Sets the text for the error message.
	 * @param string the error message
	 */
	public function setErrorMessage($value)
	{
		$this->setViewState('ErrorMessage',$value,'');
	}

	/**
	 * @return string the ID path of the input control to validate
	 */
	public function getControlToValidate()
	{
		return $this->getViewState('ControlToValidate','');
	}

	/**
	 * Sets the ID path of the input control to validate.
	 * The ID path is the dot-connected IDs of the controls reaching from
	 * the validator's naming container to the target control.
	 * @param string the ID path
	 */
	public function setControlToValidate($value)
	{
		$this->setViewState('ControlToValidate',$value,'');
	}

	/**
	 * @return boolean whether to set focus at the validating place if the validation fails. Defaults to false.
	 */
	public function getFocusOnError()
	{
		return $this->getViewState('FocusOnError',false);
	}

	/**
	 * @param boolean whether to set focus at the validating place if the validation fails
	 */
	public function setFocusOnError($value)
	{
		$this->setViewState('FocusOnError',TPropertyValue::ensureBoolean($value),false);
	}

	/**
	 * Gets the ID of the HTML element that will receive focus if validation fails and {@link getFocusOnError FocusOnError} is true.
	 * Defaults to the client ID of the {@link getControlToValidate ControlToValidate}.
	 * @return string the ID of the HTML element to receive focus
	 */
	public function getFocusElementID()
	{
		if(($id=$this->getViewState('FocusElementID',''))==='')
			$id=$this->getValidationTarget()->getClientID();
		return $id;
	}

	/**
	 * Sets the ID of the HTML element that will receive focus if validation fails and {@link getFocusOnError FocusOnError} is true.
	 * @param string the ID of the HTML element to receive focus
	 */
	public function setFocusElementID($value)
	{
		$this->setViewState('FocusElementID', $value, '');
	}

	/**
	 * @return string the group which this validator belongs to
	 */
	public function getValidationGroup()
	{
		return $this->getViewState('ValidationGroup','');
	}

	/**
	 * @param string the group which this validator belongs to
	 */
	public function setValidationGroup($value)
	{
		$this->setViewState('ValidationGroup',$value,'');
	}

	/**
	 * @return boolean whether the validation succeeds
	 */
	public function getIsValid()
	{
		return $this->_isValid;
	}

	/**
	 * Sets the value indicating whether the validation succeeds
	 * @param boolean whether the validation succeeds
	 */
	public function setIsValid($value)
	{
		$this->_isValid=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return TControl control to be validated. Null if no control is found.
	 * @throws TConfigurationException if {@link getControlToValidate
	 * ControlToValidate} is empty or does not point to a valid control
	 */
	protected function getValidationTarget()
	{
		if(($id=$this->getControlToValidate())!=='' && ($control=$this->findControl($id))!==null)
			return $control;
		else
			throw new TConfigurationException('basevalidator_controltovalidate_invalid',get_class($this));
	}

	/**
	 * Retrieves the property value of the control being validated.
	 * @param TControl control being validated
	 * @return string property value to be validated
	 * @throws TInvalidDataTypeException if the control to be validated does not implement {@link IValidatable}.
	 */
	protected function getValidationValue($control)
	{
		if($control instanceof IValidatable)
			return $control->getValidationPropertyValue();
		else
			throw new TInvalidDataTypeException('basevalidator_validatable_required',get_class($this));
	}

	/**
	 * Validates the specified control.
	 * Do not override this method. Override {@link evaluateIsValid} instead.
	 * @return boolean whether the validation succeeds
	 */
	public function validate()
	{
		if($visible=$this->getVisible(true))
			$this->onValidate();
		$this->setIsValid(true);
		if($this->getValidationTarget() && $visible && $this->getEnabled())
		{
			if($this->evaluateIsValid())
			{
				$this->setIsValid(true);
				$this->onSuccess();
			}
			else
			{
				$this->setIsValid(false);
				$this->onError();
			}
		}
		return $this->getIsValid();
	}

	/**
	 * @return string the css class that is applied to the control being validated in case the validation fails
	 */
	public function getControlCssClass()
	{
		return $this->getViewState('ControlCssClass','');
	}

	/**
	 * @param string the css class that is applied to the control being validated in case the validation fails
	 */
	public function setControlCssClass($value)
	{
		$this->setViewState('ControlCssClass',$value,'');
	}

	/**
	 * This is the major method for validation.
	 * Derived classes should implement this method to provide customized validation.
	 * @return boolean whether the validation succeeds
	 */
	abstract protected function evaluateIsValid();

	/**
	 * This event is raised when the validator succeeds in validation.
	 */
	public function onSuccess()
	{
		$this->raiseEvent('OnSuccess',$this,null);
	}

	/**
	 * This event is raised when the validator fails in validation.
	 */
	public function onError()
	{
		$this->raiseEvent('OnError',$this,null);
	}

	/**
	 * This event is raised right before the validator starts to perform validation.
	 * You may use this event to change the behavior of validation.
	 * For example, you may disable the validator if certain condition is satisfied.
	 * Note, the event will NOT be raised if the validator is invisible.
	 */
	public function onValidate()
	{
		$this->raiseEvent('OnValidate',$this,null);
	}

	/**
	 * Renders the validator control.
	 * @param THtmlWriter writer for the rendering purpose
	 */
	public function renderContents($writer)
	{
		if(($text=$this->getText())!=='')
			$writer->write($text);
		else if(($text=$this->getErrorMessage())!=='')
			$writer->write($text);
		else
			parent::renderContents($writer);
	}
}

/**
 * TClientSideValidatorOptions class.
 *
 * Client-side validator events can be modified through the {@link
 * TBaseValidator::getClientSide ClientSide} property of a validator. The
 * subproperties of ClientSide are those of the TClientSideValidatorOptions
 * properties. The client-side validator supports the following events.
 *
 * The <tt>OnValidate</tt> event is raise before the validator validation
 * functions are called.
 *
 * The <tt>OnSuccess</tt> event is raised after the validator has successfully
 * validate the control.
 *
 * The <tt>OnError</tt> event is raised after the validator fails validation.
 *
 * See the quickstart documentation for further details.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Revision: $  $Date: $
 * @package System.Web.UI.WebControls
 * @since 3.0
 */
class TClientSideValidatorOptions extends TClientSideOptions
{
	/**
	 * @return string javascript code for client-side OnValidate event.
	 */
	public function getOnValidate()
	{
		return $this->getOption('OnValidate');
	}

	/**
	 * Client-side OnValidate validator event is raise before the validators
	 * validation functions are called.
	 * @param string javascript code for client-side OnValidate event.
	 */
	public function setOnValidate($javascript)
	{
		$this->setFunction('OnValidate', $javascript);
	}

	/**
	 * Client-side OnSuccess event is raise after validation is successfull.
	 * This will override the default client-side validator behaviour.
	 * @param string javascript code for client-side OnSuccess event.
	 */
	public function setOnSuccess($javascript)
	{
		$this->setFunction('OnSuccess', $javascript);
	}

	/**
	 * @return string javascript code for client-side OnSuccess event.
	 */
	public function getOnSuccess()
	{
		return $this->getOption('OnSuccess');
	}

	/**
	 * Client-side OnError event is raised after validation failure.
	 * This will override the default client-side validator behaviour.
	 * @param string javascript code for client-side OnError event.
	 */
	public function setOnError($javascript)
	{
		$this->setFunction('OnError', $javascript);
	}

	/**
	 * @return string javascript code for client-side OnError event.
	 */
	public function getOnError()
	{
		return $this->getOption('OnError');
	}

	/**
	 * @param boolean true to revalidate when the control to validate changes value.
	 */
	public function setObserveChanges($value)
	{
		$this->setOption('ObserveChanges', TPropertyValue::ensureBoolean($value));
	}

	/**
	 * @return boolean true to observe changes.
	 */
	public function getObserveChanges()
	{
		if(($option=$this->getOption('ObserveChanges'))!==null)
			return $option;
		else
			return true;
	}

	/**
	 * Ensure the string is a valid javascript function. If the string begins
	 * with "javascript:" valid javascript function is assumed, otherwise the
	 * code block is enclosed with "function(validator, sender){ }" block.
	 * @param string javascript code.
	 * @return string javascript function code.
	 */
	protected function ensureFunction($javascript)
	{
		return "function(validator, sender){ {$javascript} }";
	}
}

?>