# String validation with dedicated type

**URL:** <https://discourse.julialang.org/t/string-validation-with-dedicated-type/82136>\
**Category:** New to Julia\
**Tags:** strings, type, parsing\
**Created:** [June 2, 2022, 2:13pm UTC](https://discourse.julialang.org/t/string-validation-with-dedicated-type/82136 "2022-06-02T14:13:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![lvignoli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lvignoli/32/36760_2.png) [@lvignoli](https://discourse.julialang.org/u/lvignoli)\
**Post date:** [June 2, 2022, 2:13pm UTC](https://discourse.julialang.org/t/string-validation-with-dedicated-type/82136/1 "2022-06-02T14:13:47Z")

</div>

Hi,

I am writing functions that expect string arguments containing only `'X'`, `'Y'` and `'Z'`, such as `"XYZXYZZYX"`. Rather than checking in each functions that the arguments are matched by a certain regex, it seems only natural to create a dedicated type, say `XYZString`. Then functions like

```julia
function f(s::XYZString) begin
...
end

```

are sure to operate on a good, “parsable” argument `s` when called as

```julia
s = XYZString("XYZYYXZ")
f(s)

```

and I can remove validation and defensive coding from them.

So far I am failing to understand the proper way to construct this type.

1. **Can it be a simple type?**  
Is there valid code in the vein of:

```julia
type XYZString String # meaning XYZString is just a string under the hood
XYZString(s::AbstractString)::XYZString = ...

```

1. **Should it be some kind of type alias?**

2. **Should it be a struct with an embedded string type implementing all the methods of the `AbstractString` interface?**  
Like so:

```julia
struct XYZString <: AbstractString
   s::String
   function XYZString(s::string)::XYZString
      if Set(s) ⊈ Set('X','Y','Z') throw(DomainError, "bad string") end
      new(s)
   end
end

# many methods on XYZString to implement AbstractString, but which ones!?
# ...

```

It looks so verbose I cannot believe it is the right answer, plus I don’t know which methods are required and which are not, the docs are unclear to me, and finally I am bother by the necessity to embed a name value in a whole struct when all we need is just a string.

1. **How would this discussion extends for `Vector{Char}` instead of string?**  
Namely, expecting arrays like `['X', 'Y', 'Z', 'Y']` instead of strings like `"XYZY"`. Would it be easier?

* * *

It is similar to [this question](https://discourse.julialang.org/t/help-with-my-string-type/10743), though I find the answers do not help for beginner in Julia like me.

> [@Help with my string type](https://discourse.julialang.org/t/help-with-my-string-type/10743/1):
>
> Hi there,
> 
> I’m trying to implement a new string type consisting only of the characters [A-Z] and [0-9]:  
> …
