(Quick Reference)

7.2 Validating Constraints - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

7.2 Validating Constraints

Validation Basics

Call the validate method to validate a domain class instance:

เรียกใช้ validate เพื่อการตรวจสอบความผิดพลาดของ โดเมน

def user = new User(params)

if (user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }

The errors property on domain classes is an instance of the Spring Errors interface. The Errors interface provides methods to navigate the validation errors and also retrieve the original values.

ค่า errors ในโดเมนเป้น instance ของอินเตอร์เฟส Errors ในสปริง Errors อินเตอร์เฟสจะสามารถเรียกใช้ method เพื่อการหาข้อผิดพลาดและการเรียกข้อมูลที่ผิดพลาดขึ้นมาได้ด้วย

Validation Phases

Within Grails there are two phases of validation, the first one being data binding which occurs when you bind request parameters onto an instance such as:

ใน Grails จะมีสองระดับในการตรวจสอบความผิดพลาด ระดับที่หนึ่งคือ data binding ที่จะเกิดขึ้นเมื่อคุณเรียกข้อมูลจาก instance หนึ่งๆเช่น

def user = new User(params)

At this point you may already have errors in the errors property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the Errors API:

โดยในจุดนี้คุณสามารถมีข้อผิดพลาดได้จากการเปลี่ยนกลับของ type เช่น เปลี่ยนจาก Strings เป็น Dates คุณสามารถตรวจสอบได้โดยการใช้ Errors

if (user.hasErrors()) {
    if (user.errors.hasFieldErrors("login")) {
        println user.errors.getFieldError("login").rejectedValue
    }
}

The second phase of validation happens when you call validate or save. This is when Grails will validate the bound values againts the constraints you defined. For example, by default the save method calls validate before executing, allowing you to write code like:

ระดับที่สองจะเกิดขึ้นเมื่อคุณเรียกใช้ validate หรือ save ในขั้นตอนนี้ Grails จะทำการตรวจสอบค่ากับ constraints ที่คุณกำหนดไว้ เช่น โดยปกติแล้ว save จะเรียกใช้ validate ก่อนที่จะทำการใดๆโดยคุณก็จะสามารถเขียนโค๊ดได้ตามตัวอย่างด้านล่าง

if (user.save()) {
    return user
}
else {
    user.errors.allErrors.each {
        println it
    }
}