Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve validation #41

Open
iRevive opened this issue Feb 13, 2023 · 0 comments
Open

Improve validation #41

iRevive opened this issue Feb 13, 2023 · 0 comments

Comments

@iRevive
Copy link
Collaborator

iRevive commented Feb 13, 2023

Use Custom Validators

var _ validator.List = checkModeValidator{}

type checkModeValidator struct {
	mode string
}

func (v checkModeValidator) Description(_ context.Context) string {
	return fmt.Sprintf("mode must be set to %s", v.mode)
}

func (v checkModeValidator) MarkdownDescription(ctx context.Context) string {
	return v.Description(ctx)
}

func (v checkModeValidator) ValidateList(ctx context.Context, req validator.ListRequest, resp *validator.ListResponse) {
	if req.ConfigValue.IsNull() || req.ConfigValue.IsUnknown() {
		// If code block does not exist, config is valid.
		return
	}

	modePath := req.Path.ParentPath().AtName("mode")

	var m types.String

	diags := req.Config.GetAttribute(ctx, modePath, &m)
	resp.Diagnostics.Append(diags...)

	if resp.Diagnostics.HasError() {
		return
	}

	if m.IsNull() || m.IsUnknown() {
		// Only validate if mode value is known.
		return
	}

	if m.ValueString() != v.mode {
		resp.Diagnostics.AddAttributeError(
			modePath,
			"Mode value invalid",
			v.Description(ctx),
		)
	}
}

func CheckMode(m string) validator.List {
	return checkModeValidator{
		mode: m,
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant