Last active
March 28, 2019 19:49
-
-
Save apzuk3/2d4f94cfd51e46741ad02de18001b54d to your computer and use it in GitHub Desktop.
Input validation in GoLang junior approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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