<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2007 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormValidatorRegex Class
 *
 * Verify the input is a valid against a regular expression.
 *
 * @package fusionLib
 */
class flFormValidatorRegex extends flFormValidator {

	/**
	 * The regualr expression to test against.
	 *
	 * @var string
	 */
	protected $regex;

	/**
	 * Construct the validator.
	 *
	 * @param string $regex The regular expression to test against.
	 * @param string $message The massage to give on failure.
	 * @param string $default Optional default message.
	 */
	function __construct($regex, $message = null, $default = null) {
		parent::__construct($message, $default === null ? __('{label} is not valid.', 'fusionLib') : $default);
		$this->regex = $regex;
	}

	/**
	 * Validate the input.
	 *
	 * @param flFormElement $elem The form element to validate.
	 * @return bool true if the input is valid; else false.
	 */
	function validate($elem) {
		parent::validate($elem);
		$value = $elem->getValue();
		return empty($value) || preg_match($this->regex, $value);
	}

	/**
	 * Get the client side rule for validation.
	 *
	 * @return array [0] The string holding the rule information for use with fusionLib.validation.js
	 * [1] true to use ajax or false, if false is returned instead of an array then no client side validation is done
	 */
	function getClientRule() {
		return array("regex: {val: $this->regex" . ($this->message === null ? '' : ', ' . $this->getClientMsg()) . '}', false);
	}
}
