How to use NetBeans to create a custom annotation-based validation

NetBeans supports custom annotation-based validation: define a constraint, implement its validator, attach it to a domain type and test it. The rule can run in desktop clients, REST services and Jakarta EE components.

An Australian postcode demonstrates the need. Its four-digit shape is simple, but valid prefixes differ across states and territories, so a regular expression cannot express the rule.

The example uses Jakarta Bean Validation instead of the older javax.validation API. That distinction matters between plain Java and Jakarta EE because provider and package names change.

NetBeans combines Maven dependencies, source navigation and JUnit support. The example targets Java 17 or newer and fits an existing Java EE or EJB project.

Set up a validation-ready project

Create a Java with Maven project, select a validation package and use Add Dependency on the project node. Add jakarta.validation-api and hibernate-validator; standalone Java also needs expressly, while Jakarta EE normally supplies the provider. Use compatible versions. The NetBeans Blog’s browse by category pages can help readers find related IDE material.

Choose the narrowest mechanism that expresses the requirement:

Mechanism Suitable for Limitation
Built-in @NotBlank Required text Cannot test postcode allocation
@Pattern Four-digit shape Cannot express valid prefixes
Custom constraint Australian postcode prefix rule Requires a validator and tests

Semantic validation justifies a custom constraint. Keep standard annotations for presence and format, then compose the custom check.

Define the constraint contract

Create AustralianPostcode in a package such as au.com.example.validation:

package au.com.example.validation;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = AustralianPostcodeValidator.class)
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD,
         ElementType.METHOD, ElementType.PARAMETER,
         ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AustralianPostcode {
    String message() default "{au.com.example.validation.AustralianPostcode.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Metadata identifies the validator class. The message key points to ValidationMessages.properties; groups support staged validation, and payload allows future metadata. Runtime retention and the field, parameter and type-use targets support JavaBeans, records and method parameters.

Blank and null values are left to @NotBlank so each constraint reports a different cause. Document this choice beside the source; a personal engineering page such as Phil Schwartz can preserve the rationale, while version control remains authoritative.

Implement the postcode validator

Create a stateless validator:

package au.com.example.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public final class AustralianPostcodeValidator
        implements ConstraintValidator<AustralianPostcode, String> {
    @Override
    public boolean isValid(String value,
            ConstraintValidatorContext context) {
        if (value == null || value.isBlank()) return true;
        String candidate = value.replaceAll("\\s+", "");
        if (!candidate.matches("[0-9]{4}")) return false;
        int prefix = Integer.parseInt(candidate.substring(0, 2));
        return validPrefix(prefix);
    }

    private static boolean validPrefix(int prefix) {
        return prefix == 2 || prefix == 8
            || (prefix >= 20 && prefix <= 23)
            || (prefix >= 26 && prefix <= 29)
            || (prefix >= 30 && prefix <= 79);
    }
}

The prefixes cover the Australian Capital Territory, Northern Territory, New South Wales, Victoria, Queensland, South Australia, Western Australia and Tasmania. Whitespace is removed, accepting “2000” or “20 00”, but not letters or extra characters.

This checks delivery postcodes, not a complete address database. For businesses still mailing statements or customer cards, a prefix error can delay delivery. Private postcodes, PO Box rules and new allocations vary, so compare the list with the current Australia Post reference and local carrier rules.

Apply the constraint to domain records

Apply both constraints to the record component:

import jakarta.validation.constraints.NotBlank;

public record DeliveryAddress(
    @NotBlank
    @AustralianPostcode
    String postcode
) {}

Add src/main/resources/ValidationMessages.properties with this key and value:

au.com.example.validation.AustralianPostcode.message=Enter a valid Australian postcode

The provider interpolates the custom key and returns a property path such as postcode. The @NotBlank message is optional; keeping both messages clear helps users correct a missing value and an unsupported postcode separately.

Trigger validation from application workflows

In a standalone application, obtain a Validator from Validation.buildDefaultValidatorFactory() and call validate(address). In Jakarta EE code, inject the provider-managed validator; in a REST endpoint, use @Valid at the boundary. Client-side checks help usability, but the server must revalidate untrusted input.

For database-backed screens, configure pooled connections through JDBC connection management rather than opening one inside the validator. Keep the constraint independent of persistence so it can serve batch jobs and messaging consumers.

Teams in Sydney, Melbourne and Brisbane often share services across different clock and daylight-saving settings. Keep validation results free of local timestamps and use locale-neutral error keys; record UTC separately in logs.

Test and version the validation rule

Add JUnit Jupiter and focused tests:

@Test
void acceptsCommonPostcodes() {
    var validator = new AustralianPostcodeValidator();
    assertTrue(validator.isValid("2000", null));
    assertTrue(validator.isValid("2600", null));
    assertTrue(validator.isValid("4000", null));
}

@Test
void rejectsUnknownPrefix() {
    assertFalse(new AustralianPostcodeValidator()
        .isValid("9999", null));
}

The cases cover Sydney, Canberra and Brisbane. Add an integration test that validates a DeliveryAddress through the provider, plus null, blank, spaced and malformed inputs; direct tests do not prove that the provider discovers the annotation.

Commit the annotation, validator, message bundle and tests together. Teams still using Subversion can follow Subversion in NetBeans to preserve that change set; Git-based teams should use the equivalent branch and pull-request workflow.

Apply Australian operational safeguards

Data quality and privacy are separate controls. If an Australian business is covered by the Privacy Act 1988, a postcode linked to a person can be personal information under the Australian Privacy Principles. Keep full addresses out of exception messages and logs, and apply organisational retention and access rules to validation records.

When reused in an Australian health-service application, structural validity still cannot replace domain judgement. A Spanish-language clinical review of antimicrobial use in patients illustrates the specialist evidence that must remain separate from a field-level check.

For Australian development and operations teams, these practices keep the constraint useful without turning it into a compliance system:

  • Keep the annotation and validator in one dedicated validation package.
  • Pair @AustralianPostcode with @NotBlank on required address fields.
  • Test every accepted prefix family and representative boundary values.
  • Review the prefix list whenever Australia Post changes allocations.
  • Revalidate at the server or messaging boundary, never only in the browser.
  • Log field names and error keys, not full customer addresses or health details.

This approach suits Australian SMEs with lean Java teams: NetBeans supplies the editing and debugging workflow, Maven Central supplies providers, and one portable rule can serve web, desktop and integration layers. Product owners also receive a clear, testable definition of an acceptable postcode.