validationmdl.go 1.27 KiB
Newer Older
Rahul A. Sutar's avatar
Rahul A. Sutar committed
package validationmdl

import (
	"net/http"
	"net/url"

	"github.com/thedevsaddam/govalidator"
)

//ValidateRequest func validates the given model
func ValidateRequest(httpRequest *http.Request, validationRules, validationMessages govalidator.MapData) map[string]interface{} {

	//Get the content type of the request as validations for content types are different
	contentType := httpRequest.Header.Get("Content-Type")

	//Initialize the validation errors as blank
	var validationErrors url.Values

	//Set validator options
	opts := govalidator.Options{
		Request: httpRequest,
		Rules:   validationRules,
	}

	//Set custom validation messages if sent from user
	if validationMessages != nil {
		opts.Messages = validationMessages
	}

Rahul A. Sutar's avatar
Rahul A. Sutar committed
	if contentType == "application/json" || contentType == "text/plain" {
Rahul A. Sutar's avatar
Rahul A. Sutar committed
		//Validate request type json and text (RAW data from request)
		data := make(map[string]interface{}, 0)
Rahul A. Sutar's avatar
Rahul A. Sutar committed
		opts.Data = &data
		validator := govalidator.New(opts)
		validationErrors = validator.ValidateJSON()

	} else {
		//Validate request type form-data, form-urlencoded
		validator := govalidator.New(opts)
		validationErrors = validator.Validate()
	}

	if len(validationErrors) > 0 {
		errs := map[string]interface{}{"validationErrors": validationErrors}
		return errs
	}
	return nil
}