You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为指定Schema添加0-100数值范围限制并触发异常?

如何给Schema的Int类型添加0-100范围限制?

当然可以实现这个需求!在Clojure的Schema库中,我们可以借助schema/constrained函数为Int类型添加自定义的范围约束,当数值小于0或者大于100时,Schema就会抛出异常。

原代码回顾

你原来的定义是这样的:

(def Number schema/Int)

添加范围约束后的代码

我们只需要用schema/constrained包装原有的Int Schema,传入范围判断逻辑和错误提示即可:

(def Number
  (schema/constrained schema/Int
                      #(and (>= % 0) (<= % 100))
                      "Number must be between 0 and 100 inclusive"))

代码说明

  • schema/constrained接受三个核心参数:
    1. 基础的Schema类型(这里是schema/Int)
    2. 一个判断函数,用来验证数值是否符合要求(这里检查数值是否在0到100之间,包含边界值)
    3. 自定义的错误提示信息,当验证失败时会抛出包含该信息的异常

测试验证

你可以用schema/validate函数来测试这个约束是否生效:

(schema/validate Number 50)   ; 验证通过,不会抛出异常
(schema/validate Number -5)   ; 抛出异常,提示内容为"Number must be between 0 and 100 inclusive"
(schema/validate Number 105)  ; 同样抛出异常,触发错误提示

内容的提问来源于stack exchange,提问作者Freid001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:04:22