dev-resources.site
for different kinds of informations.
A Quick Utility Module
Published at
4/30/2024
Categories
elixir
utility
validation
Author
Onorio Catenacci
I was working on some code with a friend of mine and we came up with what seems a relatively clever way to do a couple of validations. I'm putting this post here to share this in case it benefits anyone else:
defmodule Validations do
@moduledoc """
This module contains a few validation predicate functions.
"""
@doc """
Checks if a string contains only specified characters. The specified characters are passed in a list. The list can be one or more characters. You could pass an empty list if you wished but that would always return false.
## Examples
iex> Validations.string_contains_only_specified_chars?("abc", ["a", "b", "c"])
true
iex> Validations.string_contains_only_specified_chars?("abr", ["a", "b", "c"])
false
"""
@spec string_contains_only_specified_chars?(String.t(), [String.t(), ...]) :: boolean
def string_contains_only_specified_chars?(string, list)
when is_binary(string) and is_list(list) do
string
|> String.graphemes()
|> Enum.reduce(true, fn letter, acc -> letter in list && acc end)
end
@doc """
Checks if a string is of a specified length or not.
## Examples
iex> Validations.string_expected_length?("abc", 3)
true
iex> Validations.string_expected_length?("abc", 2)
false
"""
@spec string_expected_length?(String.t(), integer) :: boolean
def string_expected_length?(string, length) when is_binary(string) and is_integer(length) do
String.length(string) == length
end
end
Nothing innovative or surprising--just a little something I whipped up that I wanted to share for the potential benefit of others.
Articles
12 articles in total
A Handy Way To Clear The Terminal In Python
read article
A Quick Utility Module
currently reading
If You Laid All The . . .
read article
On The Value Of Listening To Warnings
read article
Creating Repeatable Builds
read article
Proud Moments In Mentoring!
read article
Searching For Polar Bears In Chicago
read article
Calling A Tail A Leg
read article
Git Force Push Current Branch Only
read article
Three Ways To Share Values Between Elixir Modules
read article
Just In Case
read article
Using Ack To Search Elixir Code
read article
Featured ones: