Server Side form validation 3
This commit is contained in:
		@ -1,8 +1,10 @@
 | 
			
		||||
package forms
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"net/http"
 | 
			
		||||
	"net/url"
 | 
			
		||||
	"strings"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
// Form creates a custom form struct, embeds a url.Values object
 | 
			
		||||
@ -19,17 +21,33 @@ func New(data url.Values) *Form {
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Required checks required fields
 | 
			
		||||
func (f *Form) Required(fields ...string) {
 | 
			
		||||
    for _, field := range fields {
 | 
			
		||||
        value := f.Get(field)
 | 
			
		||||
        if strings.TrimSpace(value) == "" {
 | 
			
		||||
            f.Errors.Add(field, "This field cannot be blank")
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Has checks if form field is in post and not emtpy
 | 
			
		||||
func (f *Form) Has(field string, r *http.Request) bool {
 | 
			
		||||
	x := r.Form.Get(field)
 | 
			
		||||
	if x == "" {
 | 
			
		||||
		f.Errors.Add(field, "This field cannot be blank")
 | 
			
		||||
		return false
 | 
			
		||||
	}
 | 
			
		||||
	return true
 | 
			
		||||
    return x != ""
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Valid returns true if there are no errors, otherwise false
 | 
			
		||||
func (f *Form) Valid() bool {
 | 
			
		||||
	return len(f.Errors) == 0
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// MinLength checks for string minimum length
 | 
			
		||||
func (f *Form) MinLength(field string, length int, r *http.Request) bool {
 | 
			
		||||
    value := r.Form.Get(field)
 | 
			
		||||
    if len(value) < length {
 | 
			
		||||
        f.Errors.Add(field, fmt.Sprintf("This field must have at least %d letters", length))
 | 
			
		||||
        return false
 | 
			
		||||
    }
 | 
			
		||||
    return true
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user