DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Convert Image Files Into GIF or WebP Format Using Java
  • DDD and Spring Boot Multi-Module Maven Project
  • Keep Your Application Secrets Secret

Trending

  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Data Engineering
  3. Databases
  4. How To Validate Names Using Java

How To Validate Names Using Java

Gain context of three separate API solutions which can be used to validate name input fields within an application as you follow along with this demonstration.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 03, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

Names are an important part of our identity.  When someone we meet for the first time remembers our name the next time we see them, it communicates a level of respect, indulging our feeling of self-importance and strengthening the connection we feel with that person in return. Conversely, when we forget or incorrectly remember someone’s name - or when they do the same to us - that disappointing, negative impression might never go away. 

As such, in any customer-centric business (and one might reasonably consider all businesses to be customer-centric), finding a way to record names correctly is the first step toward maintaining a positive, fruitful relationship with those customers in the future.  As the burden of recording and administrating names falls more and more exclusively to automated, client-facing web pages (for example, the "create an account" page found on many businesses' websites), a few important questions arise, such as: 

  • How do we ensure that names are stored accurately through the entry fields we set out?
  • Moreover, how do we ask our entry fields to validate that names are “correct,” when names we recognize and train our reference databases with often have unique homonyms we haven't seen before? 

Thousands of businesses – online-only and brick-and-mortar alike – lean on accurate customer data entry as the lynchpin of their sustained success.  Needless to say: it’s very important to get this right.

When it comes to ensuring accuracy and quality during any type of data entry, validation APIs are a ubiquitous solution.  They offer an efficient way to ensure improper data does not cause downstream errors in any given application. Names, however, are different than other data (especially other customer contact data like email addresses and phone numbers) in that they are not always in lockstep with a prescribed/standardized structure.  

For example, if we consider the following spellings: Conor, Conner, and Connor, we can recognize that there are at least three different ways to iterate a name that sounds the same out loud. And, based on that, we can reasonably assume that there are more niche spellings out there that we are not aware of.  As such, a name validation service must not use reference data so stringently as to categorically reject the spelling/iteration of a name simply because it doesn’t match an existing data point.  To continue with the earlier example, if a user named “Conor” creates their new account without an issue, but someone who uniquely spells their name as “Connar” is notified that their name is misspelled or invalid during that same process, we’ve begun a rocky relationship with that customer from the get-go.  Attempting to validate names in that way is tantamount to telling users how their names should be spelled.  It isn’t our place to do that; rather, name validation APIs should only take aim at preventing a limited set of invalid entries unrelated to historical spellings/iterations.  This includes avoiding numbers, symbols, spam inputs, and altogether blank entry fields.

Demonstration

This article will highlight three Name Validation APIs which are intended to facilitate name-entry validation without limiting users to known spellings of names, and with reasonable leniency around the use of common punctuation (such as hyphens and apostrophes) within names. These APIs include the following:

  • Parse & Validate a Full Name
  • Validate a First Name
  • Validate a Last Name

The parse & validate a full name API is designed to allow users to enter full names – including suffixes, nicknames, and titles – into a single field as a string.  This solution offers the opportunity to capture more information about each person entering their name and provides the greatest flexibility to accommodate those who wish to enter longer family names and titles. This API will automatically parse the input name string into a list of its component parts, including DisplayName (the full display of the name), FirstName, LastName, MiddleName, NickName, and more (a full example response body is provided below, beneath the code examples provided to call the API).  To accommodate longer family names, the MiddleName response will contain each name provided between the first & last names entered, separated by spaces.  Most importantly, this API will provide ValidationResult_FirstName and ValidationResult_LastName values, which (as the names suggest) will determine if the names are valid data entries.  ValidationResult responses can include any of the below classifications:

  • ValidFirstName, ValidLastName
  • ValidUnknownFirst Name; ValidUnknownLastName
  • InvalidSpamInput
  • InvalidCharacters
  • InvalidEmpty

With this response model, names iterated with unknown spellings will still be considered valid as long as they are spelled with valid characters.  This makes it possible to accept new spellings of names while acknowledging that they were unexpected to some degree, which should help to prevent user errors during name entry. Names will only be considered invalid if they can be identified as spam, if they contain invalid characters (numbers, symbols, etc.), or if they are left out of the name entry field entirely.

The first and last name validation APIs are, on the other hand, only concerned with validating individual names entered within their respective fields.  These APIs are perfect for situations where we want to intentionally limit/simplify user data entry (for example, if we are using these names for shipping labels).  These APIs will also return one of the ValidationResult values provided above, and they will NOT parse or restructure either entry string.

I will now demonstrate how to first install the Cloudmersive Validation API client and subsequently structure API calls to each of the three APIs outlined above.  For your convenience, I'll do so using ready-to-run Java code examples, which you can copy and paste directly into your environment.

To begin, we will first need to install the SDK library with either Maven or Gradle.  If we elect to use Maven, our first step is to add a JitPack reference to the pom.xml repository:

 
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>


Then, we need to add another reference to the dependency:

 
<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v4.25</version>
</dependency>
</dependencies>


If we elect to use Gradle, our first step is to add a reference in your root build.gradle (at the end of repositories):

 
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}


After that, we can include the dependency in build.gradle:

 
dependencies {
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}


With installation complete, we can turn our attention to calling each individual name validation function as we see fit.  Before copying any of the examples below, you’ll first need to add the following imports to the top of your file:

 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.NameApi;


1. Below our imports, we can use the following code examples to structure our parse and validate a full name API call:

 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

NameApi apiInstance = new NameApi();
FullNameValidationRequest input = new FullNameValidationRequest(); // FullNameValidationRequest | Validation request information
try {
    FullNameValidationResponse result = apiInstance.nameValidateFullName(input);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling NameApi#nameValidateFullName");
    e.printStackTrace();
}


Successfully calling the parse & validate a full name API will return the input information (as much as is made available) in the following format:

 
{
  "Successful": true,
  "ValidationResult_FirstName": "string",
  "ValidationResult_LastName": "string",
  "Title": "string",
  "FirstName": "string",
  "MiddleName": "string",
  "LastName": "string",
  "NickName": "string",
  "Suffix": "string",
  "DisplayName": "string"
}


2. To validate a first name, we can use the following function:

 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

NameApi apiInstance = new NameApi();
FirstNameValidationRequest input = new FirstNameValidationRequest(); // FirstNameValidationRequest | Validation request information
try {
    FirstNameValidationResponse result = apiInstance.nameValidateFirstName(input);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling NameApi#nameValidateFirstName");
    e.printStackTrace();
}


3. And finally, to validate a last name, we can use the below function:

 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

NameApi apiInstance = new NameApi();
LastNameValidationRequest input = new LastNameValidationRequest(); // LastNameValidationRequest | Validation request information
try {
    LastNameValidationResponse result = apiInstance.nameValidateLastName(input);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling NameApi#nameValidateLastName");
    e.printStackTrace();
}


Both the first and last name, validators will provide responses in the following format:

 
{
  "Successful": true,
  "ValidationResult": "string"
}


After installing and structuring calls to any of these APIs, I recommend testing them with a variety of different names with unique structures and spellings.  You may also wish to perform such tests before installation. To do so, on this console page, choose the API dropdowns to pass test arguments through the input parameters.

API Apache Maven Reference data Software development kit application Data (computing) Dependency Java (programming language) Repository (version control) Strings

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Convert Image Files Into GIF or WebP Format Using Java
  • DDD and Spring Boot Multi-Module Maven Project
  • Keep Your Application Secrets Secret

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!