Package de.panikco.pmdb.web.validation

Source Code of de.panikco.pmdb.web.validation.MediaValidator

package de.panikco.pmdb.web.validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import de.panikco.pmdb.model.Media;

public class MediaValidator implements Validator {

  static final String FIELD_TITLE = "title";
  static final String ERROR_EMPTY = "empty";
  static final String ERROR_TOO_LONG = "too long";
  static final int TITLE_MAX_LENGTH = 255;

  @Override
  public boolean supports(Class<?> clazz) {
    return Media.class.isAssignableFrom(clazz);
  }

  @Override
  public void validate(Object target, Errors errors) {

    if (!supports(target.getClass()))
      throw new IllegalArgumentException("Validation of classs '"
          + target.getClass() + "' is not supported");

    Media media = (Media) target;

    ValidationUtils.rejectIfEmpty(errors, FIELD_TITLE, ERROR_EMPTY);
    rejectIfExceedsMaxLength(FIELD_TITLE, TITLE_MAX_LENGTH, errors, media.getTitle());

  }

  private void rejectIfExceedsMaxLength(String field, int maxLength, Errors errors, String item) {
    if (!errors.hasFieldErrors(field)) {
      if (item.length() > maxLength) {
        errors.rejectValue(field, ERROR_TOO_LONG);
      }
    }
  }

}
TOP

Related Classes of de.panikco.pmdb.web.validation.MediaValidator

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.