add ivyz9k2l
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
@@ -93,6 +94,9 @@ func RegisterCustomValidators(validate *validator.Validate) {
|
||||
// 企业名称验证器
|
||||
validate.RegisterValidation("enterprise_name", validateEnterpriseName)
|
||||
validate.RegisterValidation("validEnterpriseName", validateEnterpriseName)
|
||||
|
||||
// Base64图片格式验证器(JPG、BMP、PNG)
|
||||
validate.RegisterValidation("validBase64Image", validateBase64Image)
|
||||
}
|
||||
|
||||
// validatePhone 手机号验证
|
||||
@@ -938,3 +942,51 @@ func (bv *BusinessValidator) ValidateStruct(data interface{}) error {
|
||||
func (bv *BusinessValidator) ValidateField(field interface{}, tag string) error {
|
||||
return bv.validator.Var(field, tag)
|
||||
}
|
||||
|
||||
// validateBase64Image Base64图片格式验证器(JPG、BMP、PNG)
|
||||
func validateBase64Image(fl validator.FieldLevel) bool {
|
||||
base64Str := fl.Field().String()
|
||||
|
||||
// 如果为空,由 omitempty 处理
|
||||
if base64Str == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
// 去除首尾空格
|
||||
base64Str = strings.TrimSpace(base64Str)
|
||||
if base64Str == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// 解码 base64 字符串
|
||||
decoded, err := base64.StdEncoding.DecodeString(base64Str)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查数据长度(至少要有文件头)
|
||||
if len(decoded) < 4 {
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查文件头,判断图片格式
|
||||
// JPG: FF D8 FF
|
||||
// PNG: 89 50 4E 47
|
||||
// BMP: 42 4D (BM)
|
||||
if len(decoded) >= 3 && decoded[0] == 0xFF && decoded[1] == 0xD8 && decoded[2] == 0xFF {
|
||||
// JPG格式
|
||||
return true
|
||||
}
|
||||
|
||||
if len(decoded) >= 4 && decoded[0] == 0x89 && decoded[1] == 0x50 && decoded[2] == 0x4E && decoded[3] == 0x47 {
|
||||
// PNG格式
|
||||
return true
|
||||
}
|
||||
|
||||
if len(decoded) >= 2 && decoded[0] == 0x42 && decoded[1] == 0x4D {
|
||||
// BMP格式
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user