Conversion and Validation

Back

Loading concept...

Jakarta EE: Conversion & Validation 🎭

The Magical Translator & Gatekeeper Story

Imagine you’re at a magical post office. People come in speaking different languages and writing letters in strange formats. Before any letter can be delivered, two important helpers work together:

  1. The Translator (Converter) - Changes words from one language to another
  2. The Gatekeeper (Validator) - Checks if the letter follows the rules

That’s exactly what Faces Converters and Faces Validators do in Jakarta EE!


πŸ”„ What Are Faces Converters?

Think of a converter like a language translator at an airport.

The Problem:

  • Humans type text: "January 15, 2024"
  • Computers need objects: LocalDate(2024, 1, 15)

The Solution: Converters translate between human text and computer objects!

graph TD A["User Types Text"] --> B["Converter"] B --> C["Java Object"] C --> B B --> D["Display Text"]

How It Works

When you submit a form:

  1. String β†’ Object (User input becomes Java object)
  2. Server processes the object
  3. Object β†’ String (Java object becomes display text)

πŸ“¦ Standard Converters

Jakarta Faces gives you FREE translators for common types. No coding needed!

The Built-In Helpers

Converter What It Does Example
f:convertNumber Numbers 1,234.56 ↔ 1234.56
f:convertDateTime Dates/Times Jan 15, 2024 ↔ Date
f:convertBoolean Yes/No true ↔ Boolean

Example: Number Converter

<h:inputText value="#{bean.price}">
  <f:convertNumber
    type="currency"
    currencySymbol="quot;/>
</h:inputText>

User types: 1234.50 User sees: $1,234.50

Example: Date Converter

<h:inputText value="#{bean.birthday}">
  <f:convertDateTime
    pattern="MM/dd/yyyy"/>
</h:inputText>

User types: 01/15/2024 Java gets: LocalDate object!


πŸ› οΈ Custom Converters

What if you have a special language nobody speaks?

Build your own translator!

When You Need One

  • Converting user IDs to User objects
  • Phone numbers with special formats
  • Custom codes like product SKUs

Building a Custom Converter

Step 1: Create the class

@FacesConverter("phoneConverter")
public class PhoneConverter
    implements Converter<Phone> {

  @Override
  public Phone getAsObject(
      FacesContext ctx,
      UIComponent comp,
      String value) {
    // String β†’ Phone object
    return new Phone(value);
  }

  @Override
  public String getAsString(
      FacesContext ctx,
      UIComponent comp,
      Phone phone) {
    // Phone object β†’ String
    return phone.format();
  }
}

Step 2: Use it in your page

<h:inputText value="#{bean.phone}"
  converter="phoneConverter"/>

The Magic Ingredients

graph TD A["Implement Converter"] --> B["getAsObject"] A --> C["getAsString"] B --> D["String to Object"] C --> E["Object to String"] A --> F["@FacesConverter"]

βœ… What Are Faces Validators?

If converters are translators, validators are gatekeepers.

The gatekeeper checks:

  • Is this letter addressed correctly?
  • Does it have a stamp?
  • Is the message appropriate?

Validators check if user input follows your rules!

When Validation Happens

graph TD A["User Submits Form"] --> B["Convert Input"] B --> C["Validate Input"] C -->|Pass| D["Process Data"] C -->|Fail| E["Show Error"]

πŸ“ Standard Validators

Free rule-checkers included with Jakarta Faces!

The Built-In Gatekeepers

Validator What It Checks
f:validateLength Text length
f:validateLongRange Number range
f:validateDoubleRange Decimal range
f:validateRequired Not empty
f:validateRegex Pattern match

Example: Length Check

<h:inputText value="#{bean.username}">
  <f:validateLength
    minimum="3"
    maximum="20"/>
</h:inputText>

Rules: Username must be 3-20 characters!

Example: Number Range

<h:inputText value="#{bean.age}">
  <f:validateLongRange
    minimum="1"
    maximum="120"/>
</h:inputText>

Rules: Age must be between 1 and 120!

Example: Pattern Match

<h:inputText value="#{bean.email}">
  <f:validateRegex
    pattern="[^@]+@[^@]+\.[^@]+"/>
</h:inputText>

Rules: Must look like an email!

Combining Validators

You can stack multiple gatekeepers:

<h:inputText value="#{bean.code}"
  required="true">
  <f:validateLength
    minimum="5" maximum="10"/>
  <f:validateRegex
    pattern="[A-Z0-9]+"/>
</h:inputText>

All rules must pass!


🎨 Custom Validators

Sometimes you need special rules nobody thought of.

When You Need One

  • Check if username already exists
  • Validate credit card numbers
  • Business-specific rules

Building a Custom Validator

Step 1: Create the class

@FacesValidator("ageValidator")
public class AgeValidator
    implements Validator<Integer> {

  @Override
  public void validate(
      FacesContext ctx,
      UIComponent comp,
      Integer value)
      throws ValidatorException {

    if (value < 18) {
      throw new ValidatorException(
        new FacesMessage(
          "Must be 18 or older!"));
    }
  }
}

Step 2: Use it in your page

<h:inputText value="#{bean.age}">
  <f:validator validatorId="ageValidator"/>
</h:inputText>

The Validation Blueprint

graph TD A["Implement Validator"] --> B["validate method"] B --> C{Value OK?} C -->|Yes| D["Continue"] C -->|No| E["Throw ValidatorException"] E --> F["Show Error Message"]

Bean Validation Integration

Even easier! Use annotations:

public class User {
  @NotNull
  @Size(min=3, max=20)
  private String username;

  @Min(18)
  private Integer age;

  @Email
  private String email;
}

The annotations validate automatically!


πŸ”— How They Work Together

Converters and Validators are best friends:

graph TD A["User Input"] --> B["CONVERT"] B --> C["VALIDATE"] C -->|Pass| D["Bean Property"] C -->|Fail| E["Error Message"] B -->|Fail| E

The Complete Flow

  1. User types "25" in age field
  2. Converter turns "25" into Integer(25)
  3. Validator checks: Is 25 β‰₯ 18? βœ…
  4. Value goes to your bean!

Real Example

<h:inputText value="#{user.birthday}">
  <!-- Convert string to date -->
  <f:convertDateTime
    pattern="yyyy-MM-dd"/>
  <!-- Check date is in past -->
  <f:validator
    validatorId="pastDateValidator"/>
</h:inputText>
<h:message for="birthday"/>

🎯 Quick Summary

Concept Job Think Of It As
Converter Translate Airport Translator
Standard Converter Built-in translate Free translators
Custom Converter Your own translate Hire your own
Validator Check rules Gatekeeper
Standard Validator Built-in checks Free security
Custom Validator Your own rules Your own guard

πŸ’‘ Key Takeaways

  1. Converters change text ↔ objects
  2. Validators enforce your rules
  3. Standard ones are free and ready
  4. Custom ones handle special cases
  5. They work together in every form!

Remember: Every time a user fills out a form, your translators and gatekeepers spring into action, making sure the right data gets through in the right format!

πŸš€ Now you understand the magic behind web form processing!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.