GithubHelp home page GithubHelp logo

ramadani / go-unique-validator Goto Github PK

View Code? Open in Web Editor NEW
8.0 2.0 4.0 4 KB

Unique validator extensions for govalidator. Inspired by Laravel's unique validation rule.

License: MIT License

Go 100.00%
golang-package validator unique-entity govalidator

go-unique-validator's Introduction

go-unique-validator

Unique validator extensions for thedevsaddam/govalidator. Inspired by Laravel's unique validation rule.

Installation

Before use this validator, you need to install thedevsaddam/govalidator first, and then install this package.

go get github.com/ramadani/go-unique-validator

Usage

Import this package to your code

import uniquevalidator "github.com/ramadani/go-unique-validator"

Create db instance

db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname?parseTime=true")
if err != nil {
  log.Fatal(err)
}
defer db.Close()

Add as custom rule to govalidator

uniqueRule := uniquevalidator.NewUniqueRule(db, "unique")
govalidator.AddCustomRule("unique", uniqueRule.Rule)

Example Rule

Format: unique:table,column,except,idColumn

To check if attribute is unique:

rules := govalidator.MapData{
	"email": []string{"required", "email", "unique:users,email"},
}

Forcing A Unique Rule To Ignore A Given ID:

rules := govalidator.MapData{
	"email": []string{"required", "email", "unique:users,email,id,123"},
}

Example Usage

package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	uniquevalidator "github.com/ramadani/go-unique-validator"
	"github.com/thedevsaddam/govalidator"
)

func handler(w http.ResponseWriter, r *http.Request) {
	rules := govalidator.MapData{
		"email": []string{"required", "email", "unique:users,email"},
	}

	opts := govalidator.Options{
		Request:         r,     // request object
		Rules:           rules, // rules map
		RequiredDefault: true,  // all the field to be pass the rules
	}
	v := govalidator.New(opts)
	e := v.Validate()
	err := map[string]interface{}{"validationError": e}
	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(err)
}

func main() {
	db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname?parseTime=true")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	uniqueRule := uniquevalidator.NewUniqueRule(db, "unique")
	govalidator.AddCustomRule("unique", uniqueRule.Rule)

	http.HandleFunc("/", handler)
	fmt.Println("Listening on port: 9000")
	http.ListenAndServe(":9000", nil)
}

Send request to the server using curl or postman: curl GET "http://localhost:[email protected]"

Response

{
    "validationError": {
        "email": [
            "The email has already been taken"
        ]
    }
}

License

The go-unique-validator is an open-source software licensed under the MIT License.

go-unique-validator's People

Contributors

ramadani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.