Table of contents
1.
Introduction
2.
JSF
3.
Steps to create a custom validator in JSF:
3.1.
Step 1: Make an UrlValidator.java validator class.
3.2.
Step 2: Use UrlValidator.java to implement Validator Interface Methods.
3.3.
Step 3: Annotate UrlValidator.java to Register the Validator.
3.4.
Step 4: In the JSF page, use the validator.
4.
Example
4.1.
UrlValidator.java
4.2.
UserData.java
4.3.
home.xhtml
4.4.
result.xhtml
5.
Frequently Asked Questions
5.1.
What distinguishes JSF from the traditional JSP/Servlet Model?
5.2.
What does JSF architecture entail?
5.3.
What is necessary to begin using JSF?
5.4.
What is Backing Bean?
6.
Conclusion
Last Updated: Mar 27, 2024

JSF Custom Validator

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello, Ninja! Have you ever needed to determine if a statement is true or false? You will run across issues while designing websites where validation is necessary. To validate various user input types, JSF has a built-in tag. You will discover custom java validation in this blog. Let's get going!

JSF

JSF (Java Server Faces) is a framework for designing user interfaces on the server-side. It's developed in Java, has a component-based architecture, and provides standard management tools for these components. It has a lot of sophisticated APIs and a lot of tag libraries.

SF (Java Server Faces) is a framework for designing user interfaces on the server-side by Java

The APIs are responsible for providing components and managing their state. Server-side validation, extensibility, accessibility, and data transformations are all made easier. Tag libraries make it easier to add components on web pages and relate them to backend objects. It has handles for applying component tags. 

Before we move on to our Java codes, you can brush up your Java skills by watching our Youtube video on Java.

 

Steps to create a custom validator in JSF:

  1. First, implement javax.faces.validator.Validator interface to make a validator class.
  2. Override the validate() function in the above-mentioned interface.
  3. Using the @FacesValidator annotation, provide the custom validator with a unique validator ID.
  4. 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!

Live masterclass