Java 怎么从jsf uicomponent验证电子邮件值

2019年8月14日22:02:36Java 怎么从jsf uicomponent验证电子邮件值已关闭评论 121 1650字阅读5分30秒

1.简介

Java 怎么从jsf uicomponent验证电子邮件值?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.application.FacesMessage;

public class Main{
    public static void validateEmail(UIComponent uic, String entry) {

        System.out.println("Email Received: " + entry);
        String field = "Email";

        if (!validateLength(uic, entry, field, 1, 50)) {
            return;
        }

        int lastDot = entry.lastIndexOf('.');
        
        if (lastDot < 1 || lastDot == entry.length() - 1) {
            String message = field + ": Invalid Email";
            invalidateInput((UIInput) uic, message);
            return;
        }

        int at = entry.indexOf('@');
        int lastAt = entry.lastIndexOf('@');
        
        if (at != lastAt || at < 1 || at > lastDot) {
            String message = field + ": Invalid Email";
            invalidateInput((UIInput) uic, message);
            return;
        }

        
        if (entry.charAt(at - 1) == '.' || entry.charAt(at + 1) == '.') {
            String message = field + " : InvalidEmail";
            invalidateInput((UIInput) uic, message);
            return;
        }

        
        if (entry.indexOf(' ') != -1) {
            String message = field + " : InvalidEmail";
            invalidateInput((UIInput) uic, message);
            return;
        }
    }
    public static boolean validateLength(UIComponent uic, String entry,
            String fieldKey, int min, int max) {

        if (entry.length() < min) {
            String message = fieldKey + " : Value has to be longer than "
                    + min + " characters";
            invalidateInput((UIInput) uic, message);
            return false;
        }

        if (entry.length() > max) {
            String message = fieldKey + " : Value has to be shorter than "
                    + max + " characters";
            invalidateInput((UIInput) uic, message);
            return false;
        }

        return true;
    }
    public static void invalidateInput(UIInput uii, String message) {
        uii.setValid(false);
        FacesContext fc = javax.faces.context.FacesContext
                .getCurrentInstance();
        fc.addMessage(uii.getClientId(fc), new FacesMessage(
                javax.faces.application.FacesMessage.SEVERITY_ERROR,
                message, null));
    }
}

 
继续阅读
编程十万个怎么办