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

2019年8月14日22:02:36 评论 29

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));
    }
}

 

3.总结

示例代码演示了 Java 怎么从jsf uicomponent验证电子邮件值,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: