Skip to content

Instantly share code, notes, and snippets.

@DylanPiercey
Created August 19, 2020 15:51
Show Gist options
  • Save DylanPiercey/27f8023ca4c9fd108973fc03a357bd63 to your computer and use it in GitHub Desktop.
Save DylanPiercey/27f8023ca4c9fd108973fc03a357bd63 to your computer and use it in GitHub Desktop.
Form validation with context example
static const Schema = object({
foo: string()
});
<ValidatedForm action="..." method="..." on-change("...") on-error("...") schema=Schema>
<ValidatedInput path="foo"/>
</ValidatedForm>
class {
onCreate() {
this.state = {
errors: {},
values: {}
};
}
async validate(path, value) {
try {
deepSetSomehow(this.state.values, path);
this.state.errors[path] = undefined;
await this.input.schema.validateAt(path, this.state.values);
this.setStateDirty("values");
this.emit("change", this.state.values);
} catch (err) {
this.state.errors[path] = err.errors || [err.message];
this.setStateDirty("errors");
this.emit("error", this.state.errors);
}
}
}
<context errors=state.errors values=state.values on-change("validate")>
<form method=input.method action=input.action>
<${input.renderBody}/>
</form>
</context>
class {
handleInput(emit, ev) {
emit("validate", this.input.path, ev.target.value);
}
}
<context|{ values, errors }, emit| from="ValidatedForm">
<input name=input.path value=deepGetSomehow(values, input.path) on-input("handleInput")/>
<if(errors[path])>
<div.errors>
${errors[path].join(", ")}
</div>
</if>
</context>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment