你可以使用自定义
逻辑类型来实现此功能。然后,您可以直接在模式中包含正则表达式。
例如,以下是如何在JavaScript中实现:
var avro = require('avsc'),
util = require('util');
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'
},
{
name: 'sessionId',
type: {
type: 'string',
logicalType: 'validated-string',
pattern: '^\\d{3}-\\d{4}-\\d{5}$'
}
},
]
}, {logicalTypes: {'validated-string': ValidatedString}});
type.isValid({custId: 'abc', sessionId: '123-1234-12345'});
type.isValid({custId: 'abc', sessionId: 'foobar'});
您可以在此处阅读有关实现和使用逻辑类型的更多信息。
编辑:对于Java实现,我相信您会想查看以下类:
1.8.0+
)。 - mtth