我试图为属性编写一个通用的自定义验证器,使其通用我需要在闭包中引用字段名称,代码如下在config.groovy
grails.gorm.default.constraints = { nameShared(validator: {val, obj, errors-> Pattern p = Pattern.compile("[a-zA-Z0-9-]{1,15}") Matcher m = p.matcher(val) boolean b = m.matches() if(!b) errors.rejectValue('name', "${obj.class}.name.invalid", "Name is invalid") })在我的域类中
class Student{ String name static constraints = { name(shared:'nameShared') } } class Teacher{ String firstName String lastName static constraints = { firstName(shared:'nameShared') } }我想对name和firstName使用相同的验证器,但由于我在验证器中硬编码fieldName,它将始终用于name而不是firstName,所以我想知道是否有任何方式我可以获得对fieldname并使验证器通用,请帮助
I am trying to write a generic custom validator for a property, to make it generic i need a reference to the field name within the closure, the code is as follows In config.groovy
grails.gorm.default.constraints = { nameShared(validator: {val, obj, errors-> Pattern p = Pattern.compile("[a-zA-Z0-9-]{1,15}") Matcher m = p.matcher(val) boolean b = m.matches() if(!b) errors.rejectValue('name', "${obj.class}.name.invalid", "Name is invalid") })in My domain class
class Student{ String name static constraints = { name(shared:'nameShared') } } class Teacher{ String firstName String lastName static constraints = { firstName(shared:'nameShared') } }I want to use the same validator for both name and firstName, but since i am hardcoding the fieldName in the validator, it will always work for name and not firstName, so i want to know if there is anyway i can get a reference to the fieldname and make the validator generic, please help
最满意答案
您可以使用变量propertyName来获取validated属性的名称。
从grails docs :
Closure还可以访问约束适用于使用propertyName的字段的名称
myField validator: { val, obj -> return propertyName == "myField" }You could use the variable propertyName to get the name of the validated property.
From the grails docs:
The Closure also has access to the name of the field that the constraint applies to using propertyName
myField validator: { val, obj -> return propertyName == "myField" }更多推荐
firstName,validator,验证,constraints,电脑培训,计算机培训,IT培训"/> <meta name=
发布评论