beego表達資料驗證

正在攀登的小蝸牛發表於2020-12-14


beego提供了庫validation,用於資料驗證和錯誤收集

1. 安裝

go get -u github.com/astaxie/beego/validation

2. 實現方式

2.1 方法1:StrutTag驗證

validation.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>賬號註冊</title>
</head>
<body>
<form action="/tag" method="post" >
    <table>
        <tbody>
        <tr>
            <td>使用者名稱</td>
            <td>
                <input type="text" name ="User" value=""> <span style="color: red;"> {{.VerifyUser}} </span>
            </td>
        </tr>
        <tr>
            <td>密碼</td>
            <td>
                <input type="password" name ="Pwd" value=""><span style="color: red;">{{.VerifyPwd}}</span>
            </td>
        </tr>
        <tr>
            <td>確認密碼</td>
            <td>
                <input type="password" name ="CfmPwd" value=""><span style="color: red;">{{.VerifyCfm}}</span>
            </td>
        </tr>

        <tr>
            <td>真實姓名</td>
            <td>
                <input type="text" name ="RealName" value=""><span style="color: red;">{{.VerifyRealName}}</span>
            </td>
        </tr>
        <tr>
            <td>年齡</td>
            <td>
                <input type="text" name ="Age" value=""> <span style="color: #ff0000;">{{.VerifyAge}}</span>
            </td>
        </tr>
        <tr>
            <td>身份證</td>
            <td>
                <input type="text" name ="IdCard" value=""> <span style="color: red;">{{.VerifyIdCard}}</span>
            </td>
        </tr>
        <tr>
            <td>郵箱</td>
            <td>
                <input type="text" name ="Email" value=""> <span style="color: red;">{{.VerifyEmail}}</span>
            </td>
        </tr>
        <tr>
            <td>手機</td>
            <td>
                <input type="text" name ="Tel" value=""> <span style="color: red;">{{.VerifyTel}}</span>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="確認">
            </td>
            <td>
                <input type="reset" value="重置">
            </td>
        </tr>
        </tbody>
    </table>
</form>
</body>
</html>
package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type TagValidationController struct {
	beego.Controller
}

type Worker struct {
	User     string `valid:"Required;MinSize(6)"` //不為空且最小長度為6
	Pwd      string `valid:"Required;MinSize(6)"` //不為空且最小長度為6
	RealName string `valid:"Required"`            //不為空
	Age      string `valid:"Numeric"`             //為數字字串
	IdCard   string `valid:"Required;Length(18)"` //不為空且長度為18
	Email    string `valid:"Required;Email"`      //不為空且格式為Email
	Tel      string `valid:"Required;Mobile"`     //不為空且格式為mobile

}

func (this *TagValidationController) Get() {
	this.TplName = "validation.html"
}

func (this *TagValidationController) Post() {
	this.TplName = "validation.html"
	var worker Worker
	// 解析資料到結構體
	if err := this.ParseForm(&worker); err != nil {
		this.Data["PaseFormErr"] = "資料解析失敗"
	} else {
		valid := validation.Validation{}

		// 自定義訊息提示
		var MessageTmpls = map[string]string{
			"Required": "不能為空",
			"MinSize":  "最短長度為 %d",
			"Length":   "長度必須為 %d",
			"Numeric":  "必須是有效的數字",
			"Email":    "無效的電子郵件地址",
			"Mobile":   "無效的手機號碼",
		}
		validation.SetDefaultMessage(MessageTmpls)

		// 驗證是否struct tag是否正確
		validResult, err := valid.Valid(&worker)
		if err != nil {
			this.Data["ParseFormerErr"] = err
		}
		if !validResult {
			// 驗證沒通過
			for _, err := range valid.Errors {
				data := "Verify" + err.Field
				this.Data[data] = err.Message
			}
		}

	}
}

2.2 方法2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>賬號註冊</title>
</head>
<body>
<form action="/validation" method="post" >
    <table>
        <tbody>
        <tr>
            <td>使用者名稱</td>
            <td>
                <input type="text" name ="User" value=""> <span style="color: red;"> {{.VerifyUser}} </span>
            </td>
        </tr>
        <tr>
            <td>密碼</td>
            <td>
                <input type="password" name ="Pwd" value=""><span style="color: red;">{{.VerifyPwd}}</span>
            </td>
        </tr>
        <tr>
            <td>確認密碼</td>
            <td>
                <input type="password" name ="CfmPwd" value=""><span style="color: red;">{{.VerifyCfm}}</span>
            </td>
        </tr>

        <tr>
            <td>真實姓名</td>
            <td>
                <input type="text" name ="RealName" value=""><span style="color: red;">{{.VerifyRealName}}</span>
            </td>
        </tr>
        <tr>
            <td>年齡</td>
            <td>
                <input type="text" name ="Age" value=""> <span style="color: #ff0000;">{{.VerifyAge}}</span>
            </td>
        </tr>
        <tr>
            <td>身份證</td>
            <td>
                <input type="text" name ="IdCard" value=""> <span style="color: red;">{{.VerifyIdCard}}</span>
            </td>
        </tr>
        <tr>
            <td>郵箱</td>
            <td>
                <input type="text" name ="Email" value=""> <span style="color: red;">{{.VerifyEmail}}</span>
            </td>
        </tr>
        <tr>
            <td>手機</td>
            <td>
                <input type="text" name ="Tel" value=""> <span style="color: red;">{{.VerifyTel}}</span>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="確認">
            </td>
            <td>
                <input type="reset" value="重置">
            </td>
        </tr>
        </tbody>
    </table>
</form>
</body>
</html>
package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type ValidationController struct {
	beego.Controller
}

type Info struct {
	User     string
	Pwd      string
	RealName string
	Age      string
	IdCard   string
	Email    string
	Tel      string
}

func (this *ValidationController) Get() {
	this.TplName = "validation.html"
}

func (this *ValidationController) Post() {
	this.TplName = "validation.html"
	var info Info

	// 解析資料
	if err := this.ParseForm(&info); err != nil {
		this.Data["ParseFormErr"] = "資料解析到結構體錯誤"
	} else {
		valid := validation.Validation{}
		/*
			// 驗證使用者名稱
			userresult := valid.Required(info.User, "User")
			if !userresult.Ok {
				this.Data["VerifyUser"] = "使用者名稱不能為空"
			} else {
				userresult = valid.MinSize(info.User, 6, "User")
				if !userresult.Ok {
					this.Data["VerifyUser"] = "使用者名稱最小長度為6位"
				}
			}

			// 驗證密碼
			pwdresult := valid.Required(info.Pwd, "Pwd")
			if !pwdresult.Ok {
				this.Data["VerifyPwd"] = "密碼不能為空"
			} else {
				pwdresult = valid.MinSize(info.Pwd, 6, "Pwd")
				if !pwdresult.Ok {
					this.Data["VerifyPwd"] = "密碼最小長度為6位"
				}
			}

			// 驗證密碼是否一致
			cfmpwd := this.GetString("CfmPwd")
			if cfmpwd != "" {
				if cfmpwd != info.Pwd {
					this.Data["VerifyCfm"] = "兩次密碼不一致"
				}
			} else {
				this.Data["VerifyCfm"] = "確認密碼不能為空"
			}

			// 驗證姓名不能為空
			realnameresult := valid.Required(info.RealName, "RealName")
			if !realnameresult.Ok {
				this.Data["VerifyRealName"] = "真實姓名不能為空"
			}

			// 驗證年齡是否為數字
			ageresult := valid.Numeric(info.Age, "Age")
			if !ageresult.Ok {
				this.Data["VerifyAge"] = "年齡只能為數字"
			}

			// 驗證身份證是否合法
			idcardresult := valid.Required(info.IdCard, "IdCard")
			if !idcardresult.Ok {
				this.Data["VerifyIdCard"] = "身份證不能為空"
			} else {
				idcardresult = valid.Length(info.IdCard, 18, "IdCard")
				if !idcardresult.Ok {
					this.Data["VerifyIdCard"] = "身份證錯誤"
				}
			}

			// 驗證郵箱
			emailresult := valid.Required(info.Email, "Email")
			if !emailresult.Ok {
				this.Data["VerifyEmail"] = "郵箱不能為空"
			} else {
				emailresult = valid.Email(info.Email,"Email")
				if !emailresult.Ok {
					this.Data["VerifyEmail"] = "郵箱格式錯誤"
				}
			}

			// 驗證手機
			telresult := valid.Required(info.Tel, "Tel")
			if !telresult.Ok {
				this.Data["VerifyTel"] = "手機不能為空"
			} else {
				telresult = valid.Mobile(info.Tel, "Tel")
				if !telresult.Ok {
					this.Data["VerifyTel"] = "手機格式錯誤"
				}
			}*/

		valid.Required(info.User, "User").Message("使用者名稱不能為空")
		valid.MinSize(info.User, 6, "User").Message("使用者名稱最短為6位")
		valid.Required(info.Pwd, "Pwd").Message("密碼不能為空")
		valid.MinSize(info.User, 6, "Pwd").Message("密碼最短為6位")
		valid.Required(info.RealName, "RealName").Message("真實姓名不能為空")
		valid.Required(info.Age, "Age").Message("年齡不能為空")
		valid.Numeric(info.Age, "Age").Message("年齡只能為數字")
		valid.Required(info.IdCard, "IdCard").Message("身份證不能為空")
		valid.Length(info.IdCard, 18, "IdCard").Message("身份證格式非法")
		valid.Required(info.Email, "Email").Message("郵箱不能為空")
		valid.Email(info.Email, "Email").Message("郵箱格式非法")
		valid.Required(info.Tel, "Tel").Message("手機不能為空")
		valid.Mobile(info.Tel, "Tel").Message("手機格式非法")

		if valid.HasErrors() {
			for _, err := range valid.Errors {
				data := "Verify" + err.Key
				this.Data[data] = err.Message
			}
		}
	}
}

相關文章