您应该能够使用自定义逻辑类型为了这。然后,您可以将正则表达式直接包含在架构中。
例如,以下是在 JavaScript 中实现的方法:
var avro = require('avsc'),
util = require('util');
/**
* Sample logical type that validates strings using a regular expression.
*
*/
function ValidatedString(attrs, opts) {
avro.types.LogicalType.call(this, attrs, opts);
this._pattern = new RegExp(attrs.pattern);
}
util.inherits(ValidatedString, avro.types.LogicalType);
ValidatedString.prototype._fromValue = function (val) {
if (!this._pattern.test(val)) {
throw new Error('invalid string: ' + val);
}
return val;
};
ValidatedString.prototype._toValue = ValidatedString.prototype._fromValue;
以及如何使用它:
var type = avro.parse({
name: 'Example',
type: 'record',
fields: [
{
name: 'custId',
type: 'string' // Normal (free-form) string.
},
{
name: 'sessionId',
type: {
type: 'string',
logicalType: 'validated-string',
pattern: '^\\d{3}-\\d{4}-\\d{5}$' // Validation pattern.
}
},
]
}, {logicalTypes: {'validated-string': ValidatedString}});
type.isValid({custId: 'abc', sessionId: '123-1234-12345'}); // true
type.isValid({custId: 'abc', sessionId: 'foobar'}); // false
您可以阅读有关实现和使用逻辑类型的更多信息here.
编辑:对于 Java 实现,我相信您会想要查看以下类:
-
LogicalType,您需要扩展的基础。
-
Conversion,执行数据的转换(或在您的情况下进行验证)。
-
LogicalTypes and Conversions,现有实现的一些示例。
-
TestGenericLogicalTypes,相关测试可以提供一个有用的起点。