PageRenderTime 59ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/fortech/taxesmemo/util/validator/EmailValidator.java

https://bitbucket.org/gabi88ibag/taxesmemo
Java | 67 lines | 52 code | 15 blank | 0 comment | 9 complexity | 2f015537b671e552dd6153a139c47e4b MD5 | raw file
  1. package com.fortech.taxesmemo.util.validator;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. import javax.faces.application.FacesMessage;
  5. import javax.faces.component.UIComponent;
  6. import javax.faces.context.FacesContext;
  7. import javax.faces.validator.Validator;
  8. import javax.faces.validator.ValidatorException;
  9. import org.primefaces.PrimeFaces;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.context.annotation.Scope;
  12. import org.springframework.stereotype.Component;
  13. import com.fortech.taxesmemo.services.UserService;
  14. @Component
  15. @Scope("request")
  16. public class EmailValidator implements Validator {
  17. @Autowired
  18. private UserService userService;
  19. private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern
  20. .compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
  21. public static boolean isValidEmail(String email) {
  22. Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(email);
  23. if (matcher.find()) {
  24. return true;
  25. }
  26. return false;
  27. }
  28. @Override
  29. public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
  30. if (value.toString() == null || value.toString().length() == 0) {
  31. FacesMessage msg = new FacesMessage("Email cannot be empty.", "Please enter your email.");
  32. msg.setSeverity(FacesMessage.SEVERITY_ERROR);
  33. throw new ValidatorException(msg);
  34. } else if (!isValidEmail(value.toString())) {
  35. FacesMessage msg = new FacesMessage(
  36. "Invalid Email: please provide an email address in abcd@abc.abc format.",
  37. "Please enter a valid email address.");
  38. msg.setSeverity(FacesMessage.SEVERITY_ERROR);
  39. throw new ValidatorException(msg);
  40. }
  41. else if (userService.findbyEmail(value.toString())) {
  42. System.out.println("throw error message..mail already taken!");
  43. FacesMessage msg = new FacesMessage("Invalid Email: A user with this email is already registered.",
  44. "Please enter another email.");
  45. msg.setSeverity(FacesMessage.SEVERITY_ERROR);
  46. throw new ValidatorException(msg);
  47. }
  48. }
  49. public void reset() {
  50. PrimeFaces.current().resetInputs("userForm");
  51. }
  52. }