java 接受字符串值列表的 Spring 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40096694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:55:42  来源:igfitidea点击:

Spring validation for list of accepted string values

javaspringvalidationbean-validation

提问by lmo523

Is there a validation annotationfor Springthat will do something like:

是否有一个验证标注,会做这样的:

@ValidString({"US", "GB", "CA"})
final String country;

and validate that the string is one of the supported values in the array?

并验证字符串是否是数组中受支持的值之一?

回答by Himalay Majumdar

You need to create a custom annotation to do this, I would say have an annotation which accepts enum over string comparison, and use it something like this.

您需要创建一个自定义注释来执行此操作,我会说有一个接受枚举而不是字符串比较的注释,并像这样使用它。

public enum CountryCode {
   US,
   GB,
   CA;
}

@ValidateString(CountryCode.STRING) 
String code;

You may go thru all the responses in this question Java String validation using enum values and annotation

您可以通过使用枚举值和注释的 Java 字符串验证这个问题中的所有回答

A not so clean way is to use @Pattern annotation with all the country codes in regex.

一个不太干净的方法是使用@Pattern 注释和正则表达式中的所有国家/地区代码。

@Pattern(regexp="^(AF|AX|AL|DZ|AS|AD|AO|AI|AQ|AG|AR|AM|AW|AU|AT|AZ|BS|BH|BD|BB|BY|BE|BZ|BJ|BM|BT|BO|BQ|BA|BW|BV|BR|IO|BN|BG|BF|BI|KH|CM|CA|CV|KY|CF|TD|CL|CN|CX|CC|CO|KM|CG|CD|CK|CR|CI|HR|CU|CW|CY|CZ|DK|DJ|DM|DO|EC|EG|SV|GQ|ER|EE|ET|FK|FO|FJ|FI|FR|GF|PF|TF|GA|GM|GE|DE|GH|GI|GR|GL|GD|GP|GU|GT|GG|GN|GW|GY|HT|HM|VA|HN|HK|HU|IS|IN|ID|IR|IQ|IE|IM|IL|IT|JM|JP|JE|JO|KZ|KE|KI|KP|KR|KW|KG|LA|LV|LB|LS|LR|LY|LI|LT|LU|MO|MK|MG|MW|MY|MV|ML|MT|MH|MQ|MR|MU|YT|MX|FM|MD|MC|MN|ME|MS|MA|MZ|MM|NA|NR|NP|NL|NC|NZ|NI|NE|NG|NU|NF|MP|NO|OM|PK|PW|PS|PA|PG|PY|PE|PH|PN|PL|PT|PR|QA|RE|RO|RU|RW|BL|SH|KN|LC|MF|PM|VC|WS|SM|ST|SA|SN|RS|SC|SL|SG|SX|SK|SI|SB|SO|ZA|GS|SS|ES|LK|SD|SR|SJ|SZ|SE|CH|SY|TW|TJ|TZ|TH|TL|TG|TK|TO|TT|TN|TR|TM|TC|TV|UG|UA|AE|GB|US|UM|UY|UZ|VU|VE|VN|VG|VI|WF|EH|YE|ZM|ZW)$",message="invalid code")
private String countryCode;