/src/main/java/com/fortech/taxesmemo/util/validator/EmailValidator.java
Java | 67 lines | 52 code | 15 blank | 0 comment | 9 complexity | 2f015537b671e552dd6153a139c47e4b MD5 | raw file
- package com.fortech.taxesmemo.util.validator;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import javax.faces.application.FacesMessage;
- import javax.faces.component.UIComponent;
- import javax.faces.context.FacesContext;
- import javax.faces.validator.Validator;
- import javax.faces.validator.ValidatorException;
- import org.primefaces.PrimeFaces;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Scope;
- import org.springframework.stereotype.Component;
- import com.fortech.taxesmemo.services.UserService;
- @Component
- @Scope("request")
- public class EmailValidator implements Validator {
- @Autowired
- private UserService userService;
- private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern
- .compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
- public static boolean isValidEmail(String email) {
- Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(email);
- if (matcher.find()) {
- return true;
- }
- return false;
- }
- @Override
- public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
- if (value.toString() == null || value.toString().length() == 0) {
- FacesMessage msg = new FacesMessage("Email cannot be empty.", "Please enter your email.");
- msg.setSeverity(FacesMessage.SEVERITY_ERROR);
- throw new ValidatorException(msg);
- } else if (!isValidEmail(value.toString())) {
- FacesMessage msg = new FacesMessage(
- "Invalid Email: please provide an email address in abcd@abc.abc format.",
- "Please enter a valid email address.");
- msg.setSeverity(FacesMessage.SEVERITY_ERROR);
- throw new ValidatorException(msg);
- }
- else if (userService.findbyEmail(value.toString())) {
- System.out.println("throw error message..mail already taken!");
- FacesMessage msg = new FacesMessage("Invalid Email: A user with this email is already registered.",
- "Please enter another email.");
- msg.setSeverity(FacesMessage.SEVERITY_ERROR);
- throw new ValidatorException(msg);
- }
- }
- public void reset() {
- PrimeFaces.current().resetInputs("userForm");
- }
- }