@Size注释验证字段 [英] @Size annotation to validate a field

查看:11432
本文介绍了@Size注释验证字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证字段 - secPhoneNumber(辅助电话号码)。我需要使用JSR验证满足以下条件

I need to validate a field - secPhoneNumber (secondary phone #). I need to satisfy below conditions using JSR validation


  • 该字段可以为空/ null

  • 否则,数据长度必须为10。

我尝试了下面的代码。该字段始终在表单提交时得到验证。如果字段不为空,如何验证字段长度为10?

I tried the code below. The field is always getting validated on form submission. How do I validate the field to be of length 10 only when it is not empty?

Spring Form:

Spring Form:

<form:label path="secPhoneNumber">
Secondary phone number <form:errors path="secPhoneNumber" cssClass="error" />
</form:label>
<form:input path="secPhoneNumber" />

Bean

@Size(max=10,min=10)
    private String secPhoneNumber;


推荐答案

以下模式工作


  1. @Pattern(regexp =^(\ * * | [a-zA-Z0-9] {10})$)

  2. @Pattern(regexp =^(\ s * | \d {10})$)

// ^             # Start of the line
// \s*           # A whitespace character, Zero or more times
// \d{10}        # A digit: [0-9], exactly 10 times
//[a-zA-Z0-9]{10}    # a-z,A-Z,0-9, exactly 10 times
// $             # End of the line

参考:< a href =https://stackoverflow.com/questions/19262979/validate-only-if-the-field-is-not-null?rq=1>仅在字段不为空时验证

这篇关于@Size注释验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆