如何用Yup Schema创建支持文本与链接的博客文章textarea?
调整Yup Schema实现支持含链接的描述输入
要实现description字段支持识别文本与链接,需结合Yup的验证规则和前端的输入/渲染逻辑(Yup仅负责数据格式验证,链接解析需前端处理),以下是两种实用方案:
方案一:保留字符串类型,验证链接格式
如果希望description仍以字符串存储,仅需确保内容中的链接格式合法,可以通过matches或自定义验证规则实现:
const schema = yup.object().shape({ title: yup.string().required("Your post should have a title"), description: yup.string() .required("Your post should have a description") // 匹配常见URL格式,可根据需求调整正则 .matches( /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g, "Description contains invalid URL format" ), image: yup.string().required("Add an image for your post"), createdOn: yup.date().default(() => new Date()), });
如果不需要强制验证链接格式,原Schema的string()类型本身就支持包含链接的文本输入,只需在前端渲染时用正则解析字符串中的链接并转为可点击元素即可。
方案二:改为结构化数组,区分文本与链接
若需要更精细化管理文本和链接(比如独立控制样式、编辑行为),可将description改为数组类型,存储文本块和链接块的结构化数据:
// 定义单个内容块的验证规则 const contentBlockSchema = yup.object().shape({ type: yup.string().oneOf(["text", "link"]).required(), content: yup.string().required(), // 仅当类型为link时,验证URL格式并必填 url: yup.string().when("type", { is: "link", then: (schema) => schema.url("Invalid URL format").required(), otherwise: (schema) => schema.notRequired() }) }); const schema = yup.object().shape({ title: yup.string().required("Your post should have a title"), description: yup.array().of(contentBlockSchema).required("Your post should have a description"), image: yup.string().required("Add an image for your post"), createdOn: yup.date().default(() => new Date()), });
注意:这种方案需要修改textarea的输入处理逻辑——将用户输入的文本解析为符合contentBlockSchema的数组(比如用正则匹配链接,拆分出文本和链接块),而非直接存储原始字符串。
内容的提问来源于stack exchange,提问作者Freeman Charles
相关产品推荐
相关产品推荐

