仅在字段不为空时才进行验证 [英] Validate only if the field is not Null

查看:1390
本文介绍了仅在字段不为空时才进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JSR303 Spring Validation ,我有以下内容;

I use JSR303 Spring Validation and I have the following;

@Digits(fraction = 0, integer = 15)
private String tpMobile;

验证说必须是10-15位之间的数字,但事情是这个字段是可选。因此,当用户将其留空时也显示相同的错误消息。

Validation says Must be number between 10-15 digits, but the thing is this field is optional. So when user left it empty also the same error message shows.

所以我想要做的只是在字段不为空时才进行验证。
如果该字段为空,则跳过验证该字段

So what I want to do is validate only if the field is not empty. If the field is empty skip validating that field

推荐答案

而不是使用 @Digit ,我建议你使用 @Pattern(message =YOUR_MESSAGE,regexp =REGULAR_EXPRESSION)

Instead of using @Digit, I would like to suggest you to use @Pattern(message="YOUR_MESSAGE", regexp="REGULAR_EXPRESSION")

主要原因是我们显示了我们想要限制用户的这类值的消息,这里显示的条件消息显示的是您不想限制的值。

Main reason is that we show message for such set of values for which we want to restrict the user, here in your condition message is displayed for that value which you don't want to restrict.

所以你想限制用户输入除空格和数字之外的任何内容。为此创建一个正则表达式并使用@Pattern。

So You wants to restrict user to enter anything other than blank space and numbers.Make a regular expression for that and use @Pattern with that.

对于您的情况:

@Pattern(message="YOUR_MESSAGE", regexp="^(\\s*|\\d{10,15})$")

这篇关于仅在字段不为空时才进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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