All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.cheleb.scalamigen.Validator.scala Maven / Gradle / Ivy

There is a newer version: 0.14.0
Show newest version
package dev.cheleb.scalamigen

import scala.util.Try

trait Validator[A] {
  def validate(str: String): Either[String, A]
}

/** Validators for common types. They are the base validation used by Iron
  * derivations.
  */
object Validator {

  /** A validator for strings.
    */
  given Validator[String] with
    def validate(str: String): Either[String, String] =
      Right(str)

  /** A validator for doubles.
    */
  given Validator[Double] with
    def validate(str: String): Either[String, Double] =
      str.toDoubleOption.toRight("Not a double")

  /** A validator for integers.
    */
  given Validator[Int] with
    def validate(str: String): Either[String, Int] =
      str.toIntOption.toRight("Not a int")

  /** A validator for longs.
    */
  given Validator[Float] with
    def validate(str: String): Either[String, Float] =
      str.toFloatOption.toRight("Not a float")

  /** A validator for big integers.
    */
  given Validator[BigInt] with
    def validate(str: String): Either[String, BigInt] =
      Try(BigInt.apply(str)).toEither.left.map(_.getMessage)

  /** A validator for big decimals.
    */
  given Validator[BigDecimal] with
    def validate(str: String): Either[String, BigDecimal] =
      Try(BigDecimal.apply(str)).toEither.left.map(_.getMessage)

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy