Exemplo n.º 1
0
// Enum validates if the data is a member of the enum
func Enum(path, in string, data interface{}, enum interface{}) *errors.Validation {
	val := reflect.ValueOf(enum)
	if val.Kind() != reflect.Slice {
		return nil
	}

	var values []interface{}
	for i := 0; i < val.Len(); i++ {
		ele := val.Index(i)
		enumValue := ele.Interface()
		if data != nil {
			if reflect.DeepEqual(data, enumValue) {
				return nil
			}
			actualType := reflect.TypeOf(enumValue)
			if actualType == nil {
				continue
			}
			expectedValue := reflect.ValueOf(data)
			if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
				// Attempt comparison after type conversion
				if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) {
					return nil
				}
			}
		}
		values = append(values, enumValue)
	}
	return errors.EnumFail(path, in, data, values)
}
Exemplo n.º 2
0
func (b *basicCommonValidator) Validate(data interface{}) (res *Result) {
	if len(b.Enum) > 0 {
		for _, enumValue := range b.Enum {
			if data != nil && reflect.DeepEqual(enumValue, data) {
				return nil
			}
		}
		return sErr(errors.EnumFail(b.Path, b.In, data, b.Enum))
	}
	return nil
}
Exemplo n.º 3
0
func (b *basicCommonValidator) Validate(data interface{}) (res *Result) {
	if len(b.Enum) > 0 {
		for _, enumValue := range b.Enum {
			actualType := reflect.TypeOf(enumValue)
			if actualType == nil {
				continue
			}
			expectedValue := reflect.ValueOf(data)
			if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
				if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) {
					return nil
				}
			}
		}
		return sErr(errors.EnumFail(b.Path, b.In, data, b.Enum))
	}
	return nil
}
Exemplo n.º 4
0
func enumFail(param *spec.Parameter, data interface{}) *errors.Validation {
	return errors.EnumFail(param.Name, param.In, data, param.Enum)
}
Exemplo n.º 5
0
func enumFailItems(path, in string, items *spec.Items, data interface{}) *errors.Validation {
	return errors.EnumFail(path, in, data, items.Enum)
}