java - Validation in JSF -
i'm trying implement validation of form don't accept when fill in numbers or characters.
this login.xhtml
<?xml version='1.0' encoding='utf-8' ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:body> <ui:composition template="./templates/template.xhtml"> <ui:define name="content"> <p><h:link outcome="/index" value="to home page" /></p> <h:form> username: <h:inputtext id="username" value="#{user.name}" required="true" requiredmessage="username name required"><f:validator validatorid="usernamevalidator" /></h:inputtext><br/> password: <h:inputtext id="password" value="#{user.password}" required="true" requiredmessage="password required"><f:validator validatorid="passwordvalidator" /></h:inputtext><br/> email: <h:inputtext id="email" value="#{user.email}" required="true" requiredmessage="email required"><f:validator validatorid="emailvalidator" /></h:inputtext> <h:commandbutton id="cbtn2" value="submit" action="home"/> </h:form> </ui:define> </ui:composition> </h:body> </html>
and validation class:
package validation; 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; public class passwordvalidator implements validator{ @override public void validate(facescontext context, uicomponent component, object value) throws validatorexception { string password = (string) value; if(!password.contains("([1-9]/[a-z]-[1-9]-[1-9]-[1-9](-[1-9])?")) { facesmessage message = new facesmessage(); message.setseverity(facesmessage.severity_error); message.setsummary("value entered not valid - please enter value contains [1-9]/[a-z]."); message.setdetail("value entered not valid - please enter value contains [1-9]/[a-z]."); context.addmessage("userform:password", message); throw new validatorexception(message); } } }
anyone know why don't accept when fill in admin?
string.contains
not take regular expression; try string.matches
instead.
for regex matches numbers , characters, try ^\w+$
. says, "match start of string, @ least 1 'word' character (which number or letter), match end of string".
Comments
Post a Comment