IsRequired function is added. (#12)

Fixes #11
This commit is contained in:
Onur Cinar 2023-06-15 13:57:49 -07:00 committed by GitHub
commit b5eec292bb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 4 deletions

View file

@ -8,7 +8,7 @@ There are many validation libraries available, but I prefer to build my own tool
To get started, install the Checker library with the following command:
```golang
```bash
go get github.com/cinar/checker
```
@ -37,7 +37,7 @@ if !valid {
}
```
### Validating Individual User Data
### Validating Individual User Input
If you do not want to validate user input stored in a struct, you can individually call the checker functions to validate the user input. Here is an example:
@ -66,4 +66,4 @@ type Person struct {
This package currently provides the following checkers:
- [required]() checks if the required value is provided.
- [required](docs/checkers/required.md) checks if the required value is provided.

View file

@ -5,12 +5,17 @@ import "reflect"
// ResultRequired indicates that the required value is missing.
const ResultRequired Result = "REQUIRED"
// IsRequired checks if the given required value is present.
func IsRequired(v interface{}) Result {
return checkRequired(reflect.ValueOf(v), reflect.ValueOf(nil))
}
// makeRequired makes a checker function for required.
func makeRequired(_ string) CheckFunc {
return checkRequired
}
// checkRequired checks if the required value is provided.
// checkRequired checks if the required value is present.
func checkRequired(value, _ reflect.Value) Result {
if value.IsZero() {
return ResultRequired

View file

@ -5,6 +5,14 @@ import (
"testing"
)
func TestIsRequired(t *testing.T) {
s := "valid"
if IsRequired(s) != ResultValid {
t.Fail()
}
}
func TestCheckRequiredValidString(t *testing.T) {
s := "valid"

27
doc/checkers/required.md Normal file
View file

@ -0,0 +1,27 @@
# Required Checker
The ```required``` checker checks for the presence of required input. If the input is not present, the checker will return the ```REQUIRED``` result. Here is an example:
```golang
type Person struct {
Name string `checkers:"required"`
}
person := &Person{}
mistakes, valid := checker.Check(person)
if !valid {
// Send the mistakes back to the user
}
```
If you do not want to validate user input stored in a struct, you can individually call the ```required``` checker function ```IsRequired``` to validate the user input. Here is an example:
```golang
var name
result := checker.IsRequired(name)
if result != ResultValid {
// Send the result back to the user
}
```