/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.xwork2.validator.validators;

import nuts.core.lang.StringUtils;

import com.opensymphony.xwork2.validator.ValidationException;


/**
 * Base class for string field validators.
 */
public abstract class AbstractStringFieldValidator extends AbstractFieldValidator {
	private boolean strip = false;
	
	private boolean trim = false;

	/**
	 * @return the strip
	 */
	public boolean getStrip() {
		return strip;
	}

	/**
	 * @param strip the strip to set
	 */
	public void setStrip(boolean strip) {
		this.strip = strip;
	}

	/**
	 * @return the trim
	 */
	public boolean getTrim() {
		return trim;
	}

	/**
	 * @param trim the trim to set
	 */
	public void setTrim(boolean trim) {
		this.trim = trim;
	}

	protected String trimFieldValue(Object object) throws ValidationException {
		String value = (String)getFieldValue(getFieldName(), object);

		if (strip) {
			value = StringUtils.strip(value);
		}
		else if (trim) {
			value = StringUtils.trim(value);
		}

		return value;
	}

    /**
     * @see com.opensymphony.xwork2.validator.Validator#validate(java.lang.Object)
     */
	public void validate(Object object) throws ValidationException {
		String value = trimFieldValue(object);

		if (StringUtils.isNotEmpty(value)) {
			validateString(object, value);
		}
	}

	protected abstract void validateString(Object object, String value) throws ValidationException;
}
