我试图编写一个yup验证器来验证字段的最大长度,这取决于字符串中是否包含一个破折号。如果包含一个破折号,则最大长度为10,如果没有破折号,则最大长度应为9。
例如:
'string-111'的最大长度应为10。
'string111'的最大长度应为9。
我的当前代码如下:
import * as Yup from 'yup';
export default Yup.object().shape({
description: Yup.string()
.matches(
/^[a-zA-Z0-9-]*$/,
'Invoice # can only contain letters, numbers and dashes'
)
.max(10, 'Invoice # has a max length of 10 characters'),
});我看到yup文档https://github.com/jquense/yup有一个.when()方法,但是在他们的示例中,它似乎在非常特殊的情况下使用。在这里,用户可以在字符串中的任何位置放置破折号。
对于如何重写这个验证器有什么想法,以便当字符串中没有破折号时,最大长度应该是9?
发布于 2020-03-02 22:58:04
您可以匹配10个字符(其中连字符可以在任何地方使用肯定的查找),也可以匹配仅由a-z0-9组成的9个字符。
^(?:(?=[a-z0-9-]{10}$)[a-z0-9]*-[a-z0-9]*|[a-z0-9]{9})$解释
^开始(?:非捕获群(?=积极展望,断言右边的是[a-z0-9-]{10}$匹配10次a-z0-9或-直到字符串结束。
- `)` Close lookahead
- `[a-z0-9]*-[a-z0-9]*` Match a hyphen between chars a-z0-9
- `|` Or
- `[a-z0-9]{9}` Match 9 chars a-z0-9
)紧群$末端发布于 2020-03-02 23:47:39
我想出了一个我喜欢的解决方案,但发现它已经被@Thefourthbird发布了,所以我尝试了一个不同的方法,并想出了这样的方法:
/^(?=(?:-*[^-]-*){9}$)(?=(?:[^-]*-[^-]*){0,1}$).*/gm您可以看到,这个正则表达式包含两个正的头,都是从行的开头开始的。第一个确保字符串包含9个非连字符;第二个要求最多包含一个连字符。
这个演示提供了关于这个regex是如何工作的详细和彻底的解释,但是我们也可以通过以空闲间隔模式编写它来使它自文档化。
/
^ # match beginning of string
(?= # begin a positive lookahead
(?:-*[^-]-*){9} # match 9 strings, each with one char that is
# not a hyphen, possibly preceded and/or
# followed by hyphens
$ # match the end of a line
) # end positive lookahead
(?= # begin a positive lookahead
(?:[^-]*-[^-]*){0,1} # match 0 or 1 strings, each containing one hyphen,
# possibly preceded and/or followed by non-hyphens
$ # match the end of the string
) # end positive lookahead
.* # match 0+ characters (the entire string)
/gmx # global, multiline and free-spacing regex
# definition modes如果需要,可以根据需要将[^-]替换为[a-zA-Z0-9]、\p{Alnum}或其他东西。
https://stackoverflow.com/questions/60497586
复制相似问题