fix(util/gvalid): date validation allows invalid formats like Y-MMMM and invalid dates like 2026-13-33 (#4740)

This commit is contained in:
George
2026-07-08 10:22:01 +08:00
committed by GitHub
parent b325e50277
commit f80d16cd10
2 changed files with 18 additions and 6 deletions

View File

@ -279,6 +279,11 @@ func Test_Date(t *testing.T) {
"2010/11/01": true,
"2010=11=01": false,
"123": false,
"2026-1111": false, // Bug: invalid format should not pass
"2026-13-33": false, // Bug: invalid date should not pass
"2026-02-29": false, // Non-leap year should not pass
"2024-02-29": true, // Leap year should pass
"202611-11": false, // Invalid separator should not pass
}
for k, v := range m {
err := g.Validator().Data(k).Rules("date").Run(ctx)

View File

@ -10,7 +10,7 @@ import (
"errors"
"time"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/os/gtime"
)
// RuleDate implements `date` rule:
@ -41,12 +41,19 @@ func (r RuleDate) Run(in RunInput) error {
if obj.IsZero() {
return errors.New(in.Message)
}
return nil
}
if !gregex.IsMatchString(
`\d{4}[\.\-\_/]{0,1}\d{2}[\.\-\_/]{0,1}\d{2}`,
in.Value.String(),
) {
return errors.New(in.Message)
// Try direct time conversion for validation, which handles both format and date validity.
// Support common date formats: 2006-01-02, 20060102, 2006.01.02, 2006/01/02
if _, err := gtime.StrToTimeFormat(in.Value.String(), "Ymd"); err != nil {
// Try with different separator formats
if _, err := gtime.StrToTimeFormat(in.Value.String(), "Y-m-d"); err != nil {
if _, err := gtime.StrToTimeFormat(in.Value.String(), "Y.m.d"); err != nil {
if _, err := gtime.StrToTimeFormat(in.Value.String(), "Y/m/d"); err != nil {
return errors.New(in.Message)
}
}
}
}
return nil
}