github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_telephone.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  
    12  	"github.com/gogf/gf/v2/text/gregex"
    13  )
    14  
    15  // RuleTelephone implements `telephone` rule:
    16  // "XXXX-XXXXXXX"
    17  // "XXXX-XXXXXXXX"
    18  // "XXX-XXXXXXX"
    19  // "XXX-XXXXXXXX"
    20  // "XXXXXXX"
    21  // "XXXXXXXX"
    22  //
    23  // Format: telephone
    24  type RuleTelephone struct{}
    25  
    26  func init() {
    27  	Register(RuleTelephone{})
    28  }
    29  
    30  func (r RuleTelephone) Name() string {
    31  	return "telephone"
    32  }
    33  
    34  func (r RuleTelephone) Message() string {
    35  	return "The {field} value `{value}` is not a valid telephone number"
    36  }
    37  
    38  func (r RuleTelephone) Run(in RunInput) error {
    39  	ok := gregex.IsMatchString(
    40  		`^((\d{3,4})|\d{3,4}-)?\d{7,8}$`,
    41  		in.Value.String(),
    42  	)
    43  	if ok {
    44  		return nil
    45  	}
    46  	return errors.New(in.Message)
    47  }