Introduction of data verification and data verification rules in the Gorm framework
The Gorm framework is a powerful tool for simplifying data access and operation. It is the default database access technology of the Grails application.In Gorm, in addition to data persistence, data verification and verification are also very important.This article will introduce data verification and data verification rules in the Gorm framework and provide corresponding Java code examples.
The Gorm framework provides a variety of data verification and verification rules to ensure the integrity and effectiveness of data.These rules can be directly applied to field model classes and attributes.The following will be described in detail some commonly used data verification and verification rules.
1. Non -empty verification: Use the `nullable` attribute to set a attribute to empty or not to be empty.The example code is as follows:
class User {
String name
String email
static constraints = {
name(nullable: false)
email(nullable: true)
}
}
In the above example, the `name` attribute is set to not empty, and the` email` property is set to empty.
2. Level verification: Using the `size` attribute can limit the minimum and maximum length of the attribute.The example code is as follows:
class User {
String name
static constraints = {
name(size: 3..20)
}
}
In the above example, the `name` attribute is set to minimum length of 3 and the maximum length is 20.
3. Unique verification: Using the `unique` attribute to ensure the uniqueness of the attribute.The example code is as follows:
class User {
String username
static constraints = {
username(unique: true)
}
}
In the above example, the `username` property is set to the unique.
4. Regular expression verification: Using the `Matches` property can verify the regular expression of a attribute.The example code is as follows:
class User {
String email
static constraints = {
email(matches: "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$")
}
}
In the above example, the `email` attribute is set to be set as a regular expression to pass the verification.
5. Custom verification: In addition to the rules mentioned above, you can also use the custom verification method for data verification.The example code is as follows:
class User {
String password
static constraints = {
password(validator: { value, obj ->
if (value.length() < 8) {
return 'Password must be at least 8 characters long.'
}
})
}
}
In the above example, the verification rule of the `password` attribute uses a custom method. If the password length is less than 8, a custom error message will be returned.
The above is only a small part of the rules for data verification and data verification in the Gorm framework.The Gorm framework provides more powerful verification rules, and also supports the combination of multiple verification rules.Through reasonable use of these rules, the integrity and effectiveness of data can be improved to ensure the quality of the application data.