使用注释@RegExp进行Spring验证

时间:2013-05-09 09:06:46

标签: spring spring-mvc

我使用Spring表单验证来验证用户输入的输入字段。我需要帮助才能在特定领域中包含空间。下面是我使用的验证注释。但它似乎没有空间。

@RegExp(value="([0-9|a-z|A-Z|_|$|.])*",message="value can contain only digits,alphabets or _ or . or $")
private String cName ;

我想知道我需要在验证注释中包含哪些值以在名称中包含空格

我尝试在exp值中包含'\ s'以包含空格。但它似乎不起作用

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的正则表达式字符串无法满足您的要求。

请改用以下正则表达式:

 //([0-9|a-z|A-Z|\\_|\\$|\\.|\\s])+

@Test
public void testRegex() {
    String r = "([0-9|a-z|A-Z|\\_|\\$|\\.|\\s])+";
    assertTrue("Allows space", Pattern.matches(r, "test test"));
    assertTrue("Allows .", Pattern.matches(r, "12My.test"));
    assertTrue("Allows _", Pattern.matches(r, "My_123"));
    assertTrue("Allows $", Pattern.matches(r, "$ 1.0"));

}
相关问题