DEV Community

Onorio Catenacci
Onorio Catenacci

Posted on

1

A Quick Utility Module

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

Enter fullscreen mode Exit fullscreen mode

Nothing innovative or surprising--just a little something I whipped up that I wanted to share for the potential benefit of others.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more