Steps to create a custom validator in JSF:
- First, implement javax.faces.validator.Validator interface to make a validator class.
- Override the validate() function in the above-mentioned interface.
- Using the @FacesValidator annotation, provide the custom validator with a unique validator ID.
- Use the f:validator tag to add a custom validator class to a JSF component.
Step 1: Make an UrlValidator.java validator class.
public class UrlValidator implements Validator {
...
}

You can also try this code with Online Java Compiler
Run Code
Step 2: Use UrlValidator.java to implement Validator Interface Methods.
public class UrlValidator implements Validator {
@Override
public void validate(FacesContext facesContext,
UIComponent component, String value) throws ValidatorException {
...
}
}

You can also try this code with Online Java Compiler
Run Code
Step 3: Annotate UrlValidator.java to Register the Validator.
@FacesValidator("com.tutorialspoint.test.UrlValidator")
public class UrlValidator implements Validator {
}

You can also try this code with Online Java Compiler
Run Code
Step 4: In the JSF page, use the validator.
<h:inputText id="urlInput" value="#{userData.data}" label="URL" >
<f:validator validatorId="com.tutorialspoint.test.UrlValidator" />
</h:inputText>

You can also try this code with Online Java Compiler
Run Code
Example
To test the tag mentioned above, let's develop a test JSF application;-
Step 1: reate a project named HelloWorld under the package com.codingninjas.test.
Step 2: As shown below, assemble UrlValidator.java as a converter in the com.codingninjas.test package.
Step 3: Create UserData.java as a managed bean in the com.codingninjas.test package.
Step 4: Modify home.XHTML according to the instructions below. Leave the remainder of the files alone.
Step 5: As seen below, create a result.XHTML in the webapps directory.
Step 6: Compile and run the application to ensure that the business logic meets the specifications.
Step 7: Finally, create a war file for the application and deploy it to the Apache Tomcat Webserver.
Step 8: Launch your web application by typing the relevant URL into the address bar, as shown in the last step.
UrlValidator.java
package com.codingNinjas.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("com.codingninjas.test.UrlValidator")
public class UrlValidator implements Validator {
@Override
public void validate(FacesContext facesContext,
UIComponent component, Object value)
throws ValidatorException {
StringBuilder url = new StringBuilder();
String urlValue = value.toString();
if(!urlValue.startsWith("http://", 0)) {
url.append("http://");
}
url.append(urlValue);
try {
new URI(url.toString());
} catch (URISyntaxException e) {
FacesMessage msg =
new FacesMessage("URL validation failed","Invalid URL format");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}

You can also try this code with Online Java Compiler
Run Code
UserData.java
package com.codingNinjas.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}

You can also try this code with Online Java Compiler
Run Code
home.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:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Custom Validator Example</h2>
<h:form>
<h:inputText id = "urlInput" value = "#{userData.data}"
label = "URL" >
<f:validator validatorId = "com.codingNinjas.test.UrlValidator" />
</h:inputText>
<h:commandButton value = "submit" action = "result"/>
<h:message for = "urlInput" style = "color:red" />
</h:form
</h:body>
</html>
result.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:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:ui = "http://java.sun.com/jsf/facelets">
<h:body>
<h2>Result</h2>
<hr />
#{userData.data}
</h:body>
</html>
Let us build and run the application, after you are through with all the changes. This will generate the following result if everything with your application is in order.

Press the Submit button after entering an incorrect value. Observe the error notice below.

Press the Submit button after entering any valid value. The output will come next.

Frequently Asked Questions
What distinguishes JSF from the traditional JSP/Servlet Model?
Compared to more traditional JSP servlets, JSF is a very complex language. In contrast to JSF, which operates independently, JSP and servlets are required to accomplish the operation.
What does JSF architecture entail?
JSF was created with the MVC design pattern integrated so that applications may be well planned and more easily maintained. To comprehend this reality, it is necessary to understand the MVC design pattern, how it contributes to good application design, and how to create a web application that is simple to maintain.
What is necessary to begin using JSF?
Java SE Developer Kit (JDK), JSF 1.2, or JSF 2.0 are prerequisites for learning JSF., a common application server, such as Tomcat. An Integrated Development Environment (IDE), such as Netbeans 5.5, Eclipse 3.2.x, and others, is required to build the code.
What is Backing Bean?
Backing beans are JavaBeans components used in pages connected to User Interface elements. It distinguishes between objects that serve as UI components and those that process data and carry out application-specific tasks.
Conclusion
Finally, you have reached the article's conclusion. Congratulations!! You gained knowledge of JSF's custom validator in this blog. You looked at the tag's characteristics, a sample program, and the tag itself.
Are you eager to read more articles on JSF now? Coding Ninjas cover you, so don't worry. View the JSF to learn more
Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.
Please do upvote our blogs if you find them helpful and informative!
Happy learning!