8 Kasım 2018 Perşembe

SpringValidation Validator Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
Açıklaması şöyle.
Spring has its own mechanism to do validation. It is not declarative but very flexible and extensible. It is mostly used in SpringMVC to preform validation of command object that are bound to request parameters before they are sent to the controllers. In spring the main validation construct is the Validator interface
Validator yazarken ValidationUtils,StringUtils sınıfları kullanılabilir. Ayrıca @InitBinder ile de Validator rest noktalarına bağlanabilir

supports metodu
Açıklaması şöyle.
The supports method indicates whether the validator can validate a specific class. If so, the validate method can be called to validate an instance of that class. 
validate metodu
Açıklaması şöyle.
The implementation of this method can register any validation errors that it encounters with the passed in Errors instance.

Örnek
Şöyle yaparız.
public class PeopleValidator implements Validator {
  @Override
  public boolean supports(Class<?> clazz) {
    return true;
  }

  @Override
  public void validate(Object target, Errors errors) {
    errors.reject("DIE");
  }
}
Örnek
Şöyle yaparız.
public class PersonValidator implements Validator {

  public boolean supports(Class clazz) {
    return Date.class.equals(clazz);
  }

  public void validate(Object obj, Errors e) {
    String dateString = (String) obj;
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
    DateTime ourDate = null;
    try {
      fmt.parseDateTime(dateString);
    } catch (IllegalArgumentException e) {
      // your message here
    } finally {
      ourDate = fmt.parseDateTime(dateString);
    }
  }
}

Hiç yorum yok:

Yorum Gönder