如何在zod中转换或预处理通用字段?

问题描述 投票:0回答:1

我是 zod 的新手,正在查看项目的现有代码。我想应用修剪,并且希望其值保留在修剪中,我知道我可以使用变换或预处理。当应用 zodResolver 时,会传递这样的对象:

export const candidateFormSchema = object({
candidate: object({
 first_name: validate.textfield("First name", true, 255),
 last_name: validate.textfield("Last name", true, 255),

文本字段已定义:

    import { string, z, ZodString } from "zod";
import { Field } from "./field";

export class TextField extends Field<ZodString> {

  constructor(fieldName: string) {
    super(fieldName, string());
  }

  public isRequired() {
    this.condition = this.condition.min(1, `${this.fieldName} is required`)
    return this;
  }

  public maxLength(max: number) {
    this.condition = this.condition.max(max,`${this.fieldName} must be less than ${max} characters`)
    return this;
  }

  public minLength(min: number) {
    this.condition = this.condition.min(min, `${this.fieldName} at least ${min} characters`)
    return this;
  }

  public isOptional() {
    return this.condition.optional()
  }

  public isOptionalAndCanBeEmpty() {
    return this.condition.optional().or(z.literal(""));
  }

}

export default function textfield(fieldName: string, required?: boolean, max?: number, min?: number) {
  let condition = string().trim();

  if (required) condition = condition.min(1, `${fieldName} is required`)
  if (max) condition = condition.max(max,`${fieldName} must be less than ${max} characters`)
  if (min) condition = condition.min(min, `${fieldName} at least ${min} characters`)
  
  return required ? condition : condition.optional().or(z.literal(""));
}

我不确定可以在哪里应用修剪。

typescript zod
1个回答
0
投票

如果您想更改值只是为了测试,您将需要一些自定义的内容,例如

refine
superRefine
或者可能是正则表达式,我将在这里实现。

const MaxRgx = (max) => new RegExp(`^\\s*.{0,${max}}\\s*$`); //return true when too big
const MinRgx = (min) => new RegExp(`^\\s*.{${min},}\\s*$`); //returns false when too small

由于 zod 为字符串提供了正则表达式,我们只需更改方法即可:

//....
  public maxLength(max: number) {
    this.condition = this.condition.regex(MaxRgx(max),`${this.fieldName} must be less than ${max} characters`)
    return this;
  }

  public minLength(min: number) {
    this.condition = this.condition.regex(MinRgx(min), `${this.fieldName} at least ${min} characters`)
    return this;
  }
//....

在这个游乐场

看到它

注意:我试图保持它像你的实现一样,但我可能只会使用

superRefine

© www.soinside.com 2019 - 2024. All rights reserved.