PageRenderTime 69ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/agenda/src/main/java/blir1825MV/model/validator/ValidatorContact.java

https://bitbucket.org/laura1825/blir1825
Java | 47 lines | 37 code | 9 blank | 1 comment | 20 complexity | 126cb51c0c9f18e368e2a5685ccfa1f5 MD5 | raw file
  1. package blir1825MV.model.validator;
  2. import blir1825MV.exceptions.InvalidFormatException;
  3. import blir1825MV.model.base.Contact;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. public class ValidatorContact {
  7. public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
  8. Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
  9. public boolean validate(String name, String address, String telefon, String email) throws InvalidFormatException {
  10. if (!validName(name)) throw new InvalidFormatException("Cannot convert", "Invalid name");
  11. if (!validAddress(address)) throw new InvalidFormatException("Cannot convert", "Invalid address");
  12. if (!validTelefon(telefon)) throw new InvalidFormatException("Cannot convert", "Invalid phone number");
  13. if (!validEmail(email)) throw new InvalidFormatException("Cannot convert", "Invalid email");
  14. return true;
  15. }
  16. public static boolean validName(String str)
  17. {
  18. // Check if contains a punctuation character or a space
  19. String[] s = str.split("[\\p{Punct}\\s]+");
  20. if (str.length() == 0 || s.length >= 2) return false;
  21. return true;
  22. }
  23. public static boolean validAddress(String str) {
  24. if (str.length() == 0) return false;
  25. return true;
  26. }
  27. public static boolean validTelefon(String tel) {
  28. String[] s = tel.split("[\\p{Punct}\\s]+");
  29. if (tel.charAt(0) == '+' && s.length == 2 && tel.length() == 11 & tel.matches("^\\+\\d+")) return true; // +074567345
  30. if (tel.charAt(0) != '0' || !tel.matches("\\d+")) return false; // 0345789098
  31. if (tel.length() != 10) return false;
  32. return true;
  33. }
  34. public static boolean validEmail(String email) {
  35. Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(email);
  36. return matcher.find();
  37. }
  38. }