0

如果在 XML 中指定,Bean 验证约束模式(匹配 N 位正则表达式)不起作用。例如,

public class Foo {
    @Pattern(regexp="\\d{10}")
    private String phoneNumber;
}

phoneNumber: 1234567890

注释有效。

XML:

<bean class="Foo">
        <field name="phoneNumber">
            <constraint annotation="javax.validation.constraints.Pattern">
                <element name="regexp">\\d{10}</element>
            </constraint>
        </field>
</bean>

错误:

javax.validation.ConstraintViolationException: phoneNumber: must match the following regular expression: \d{10}

如果将模式更改为:

 <element name="regexp">\d{10}</element>

错误:

java.util.IllegalFormatConversionException: d != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.util.Formatter.format(Formatter.java:2455)
    at java.lang.String.format(String.java:2940)
    at org.apache.bval.util.Exceptions.lambda$create$1(Exceptions.java:49)
    at org.apache.bval.util.Exceptions.create(Exceptions.java:58)
    at org.apache.bval.util.Exceptions.create(Exceptions.java:49)
    at org.apache.bval.jsr.metadata.XmlBuilder.loadClass(XmlBuilder.java:531)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:545)
    at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)

什么是等效的 XML @Pattern(regexp="\\d{10}")

4

1 回答 1

0

我不知道正则表达式的味道是什么,但是,如果\d不起作用,我认为[0-9]是有效的。

利用:

[0-9]{10}

代替\\d{10}

于 2020-04-28T08:48:34.347 回答