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

import (
	"errors"
Rahul A. Sutar's avatar
Rahul A. Sutar committed
	"net/http"
	"net/url"

Mayuri Shinde's avatar
Mayuri Shinde committed
	govalidator "github.com/asaskevich/govalidator"
	requestValidator "github.com/thedevsaddam/govalidator"
Rahul A. Sutar's avatar
Rahul A. Sutar committed
)

//ValidateRequest func validates the given model
Mayuri Shinde's avatar
Mayuri Shinde committed
func ValidateRequest(httpRequest *http.Request, validationRules, validationMessages requestValidator.MapData) map[string]interface{} {
Rahul A. Sutar's avatar
Rahul A. Sutar committed

	//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
Mayuri Shinde's avatar
Mayuri Shinde committed
	opts := requestValidator.Options{
Rahul A. Sutar's avatar
Rahul A. Sutar committed
		Request: httpRequest,
		Rules:   validationRules,
	}

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

	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
Mayuri Shinde's avatar
Mayuri Shinde committed
		validator := requestValidator.New(opts)
Rahul A. Sutar's avatar
Rahul A. Sutar committed
		validationErrors = validator.ValidateJSON()

	} else {
		//Validate request type form-data, form-urlencoded
Mayuri Shinde's avatar
Mayuri Shinde committed
		validator := requestValidator.New(opts)
Rahul A. Sutar's avatar
Rahul A. Sutar committed
		validationErrors = validator.Validate()
	}

	if len(validationErrors) > 0 {
		errs := map[string]interface{}{"validationErrors": validationErrors}
		return errs
	}
	return nil
}
Mayuri Shinde's avatar
Mayuri Shinde committed
// ValidateStruct validates the structures with govalidator
func ValidateStruct(structToValidate interface{}) error {
	validationResult, err := govalidator.ValidateStruct(structToValidate)
Mayuri Shinde's avatar
Mayuri Shinde committed
	if err != nil {
		return err
	}
	if !validationResult {
		return errors.New("ERROR:ValidateStruct function error")
Rahul A. Sutar's avatar
Rahul A. Sutar committed
	}
	return nil
}