
com.pekinsoft.verifiers.OptionalEmailVerifier Maven / Gradle / Ivy
/*
* Copyright (C) 2022 PekinSOFT Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
* *****************************************************************************
* Project : AppFramework
* Class : OptionalEmailVerifier.java
* Author : Sean Carrick
* Created : Dec 21, 2022
* Modified : Dec 21, 2022
*
* Purpose: See class JavaDoc for explanation
*
* Revision History:
*
* WHEN BY REASON
* ------------ ------------------- -----------------------------------------
* Dec 21, 2022 Sean Carrick Initial creation.
* *****************************************************************************
*/
package com.pekinsoft.verifiers;
import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
/**
*
* @author Sean Carrick <sean at pekinsoft dot com>
*
* @version 1.3
* @since 1.0
*/
public class OptionalEmailVerifier extends InputVerifier {
private final JLabel problemLabel;
private final String errorMessage;
private final String regex = "^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/="
+ "?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
private final Pattern pattern;
private Matcher matcher;
private Color error = new Color(1.0f, 0.832f, 0.832f);
public OptionalEmailVerifier (JLabel problemLabel, String errorMessage) {
this.problemLabel = problemLabel;
this.errorMessage = errorMessage;
pattern = Pattern.compile(regex);
}
@Override
public boolean verify(JComponent input) {
boolean valid = true; // Assume valid
if (input != null) {
if (input instanceof JTextComponent) {
String toVerify = ((JTextComponent) input).getText();
valid = toVerify.trim().isEmpty();
if (!valid) {
matcher = pattern.matcher(toVerify);
valid = matcher.matches();
}
}
if (!valid) {
input.setBackground(error);
if (problemLabel != null && !errorMessage.trim().isEmpty()) {
problemLabel.setText(errorMessage);
}
} else {
Color bg = UIManager.getColor("TextField.background");
input.setBackground(bg == null ? UIManager.getColor("text") : bg);
if (problemLabel != null) {
problemLabel.setText("");
}
}
}
return valid;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy