Created
August 19, 2020 15:51
-
-
Save DylanPiercey/27f8023ca4c9fd108973fc03a357bd63 to your computer and use it in GitHub Desktop.
Form validation with context example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static const Schema = object({ | |
foo: string() | |
}); | |
<ValidatedForm action="..." method="..." on-change("...") on-error("...") schema=Schema> | |
<ValidatedInput path="foo"/> | |
</ValidatedForm> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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