Skip to content

Instantly share code, notes, and snippets.

@apzuk3
Last active March 28, 2019 19:49
Show Gist options
  • Save apzuk3/2d4f94cfd51e46741ad02de18001b54d to your computer and use it in GitHub Desktop.
Save apzuk3/2d4f94cfd51e46741ad02de18001b54d to your computer and use it in GitHub Desktop.
Input validation in GoLang junior approach
package user
const regexpEmail = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
type User struct {
Email string
Name string
}
func (a User) IsValid() (errs url.Values) {
// check if the name empty
if a.Name == "" {
errs.Add("name", "The name is required!")
}
// check the name field is between 3 to 120 chars
if len(a.Name) < 2 || len(a.Name) > 40 {
errs.Add("name", "The name field must be between 2-40 chars!")
}
if a.Email == "" {
errs.Add("email", "The email field is required!")
}
if !regexpEmail.MAtch(a.Email) {
errs.Add("email", "The email field should be a valid email address!")
}
return errs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment