Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-validator

Typed fluent validation rules for Pudu

0.1.1Apache-2.01

InstallClose

Comparison.pudu

Pudu50 lines2.3 KB

GitHub ↗
1/** @Validation.Rules.Comparison.Module — checks typed equality */2module PuduLangValidator.Rules.Comparison34import Std.Order {Eq}5import PuduLangValidator.Rule as Rule67/// Require equality with a fixed value.8export fn equal[T, V: Eq](builder: Rule.RuleBuilder[T, V], expected: V) -> Rule.RuleBuilder[T, V] {9  Rule.withArgument(Rule.withCode(Rule.withMessage(Rule.must(builder, |value: V| value == expected),10        "Value must equal \{ComparisonValue\}."), "Equal"), "ComparisonValue", expected.toText())11}1213/// Require inequality with a fixed value.14export fn notEqual[T, V: Eq](builder: Rule.RuleBuilder[T, V], excluded: V) -> Rule.RuleBuilder[T, V] {15  Rule.withArgument(Rule.withCode(Rule.withMessage(Rule.must(builder, |value: V| value != excluded),16        "Value must differ from \{ComparisonValue\}."), "NotEqual"), "ComparisonValue", excluded.toText())17}1819/// Require equality with another selected property on the source.20export fn equalToProperty[T, V: Eq](21  builder: Rule.RuleBuilder[T, V], path: Str, select: fn(T) -> V22) -> Rule.RuleBuilder[T, V] {23  let checked = Rule.withCode(Rule.withMessage(Rule.mustWithArguments(builder,24        fn(root: T, value: V) -> Option[Array[(Str, Str)]] {25          let other = select(root)26          if value == other { None } else { Some([("ComparisonValue", other.toText())]) }27        }),28      "Value must equal \{ComparisonValue\} from \{ComparisonProperty\}."), "Equal")29  Rule.withArgument(checked, "ComparisonProperty", path)30}3132/// Require inequality with another selected property on the source.33export fn notEqualToProperty[T, V: Eq](34  builder: Rule.RuleBuilder[T, V], path: Str, select: fn(T) -> V35) -> Rule.RuleBuilder[T, V] {36  let checked = Rule.withCode(Rule.withMessage(Rule.mustWithArguments(builder,37        fn(root: T, value: V) -> Option[Array[(Str, Str)]] {38          let other = select(root)39          if value != other { None } else { Some([("ComparisonValue", other.toText())]) }40        }),41      "Value must differ from \{ComparisonValue\} at \{ComparisonProperty\}."), "NotEqual")42  Rule.withArgument(checked, "ComparisonProperty", path)43}4445/// Require membership in an explicitly supplied set of values.46export fn oneOf[T, V: Eq](builder: Rule.RuleBuilder[T, V], allowed: Array[V]) -> Rule.RuleBuilder[T, V] {47  Rule.withCode(Rule.withMessage(Rule.must(builder, |value: V| allowed.contains(value)),48      "Value must be one of the allowed values."), "OneOf")49}50