
Comparison.pudu
Pudu50 lines2.3 KB
1/** @Validation.Rules.Comparison.Module — checks typed equality */2module PuduLangValidator.Rules.Comparison34import Std.Order {Eq}5import PuduLangValidator.Rule as Rule678export 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}121314export 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}181920export 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}313233export 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}444546export 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