How to Validate a First or Last Name using Go
If you’re about to print new shipping labels or employee IDs, or even if you’re simply endeavoring to store new customers’ data, it’s important to get first and last names correct from the get-go. When it comes to validating names, however, determining correctness isn’t quite as simple as checking strings against a database of valid possibilities. After all, while many names sound and look similar, there are often distinct spellings/iterations of names which our databases aren’t immediately equipped to recognize. As a result, validating names should ultimately be an exercise in rooting out spam, invalid characters & blank entries rather than attempting to assign ‘correctness’ through an exacting reference method.
This logic is the basis for our First and Last Name Validation APIs. Both Cloudmersive Name Validation API iterations will provide one of the following strings in response to name field entries:
- ValidFirstName
- ValidUnknownFirstName
- InvalidSpamInput
- InvalidCharacters
- InvalidEmpty
With the Go code examples provided below, you can build either of the aforementioned name validation API iterations into your application with ease. All you need to do is copy & paste into your environment, use a free-tier Cloudmersive API key to authenticate your connection (you can get one by registering a free account on our website), and you’re good to go!
Use this code to call the First Name Validation API:
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/validate/name/first"
method := "POST"
payload := strings.NewReader(`{
"FirstName": "<string>"
}`)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
And use this code to call the Last Name Validation API:
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/validate/name/last"
method := "POST"
payload := strings.NewReader(`{
"LastName": "<string>"
}`)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}