sy

svelte-yup

Svelte component library for form validation with yup

Showing:

Popularity

Downloads/wk

91

GitHub Stars

17

Maintenance

Last Commit

10mos ago

Contributors

0

Package

Dependencies

0

Size (min+gzip)

4.2KB

License

MIT

Type Definitions

Tree-Shakeable

Yes?

Categories

Readme

svelte-yup

npm NPM GitHub top language npm

Svelte component library using Yup for form validation.

Installation

$ npm i svelte-yup --save-dev
$ npm i yup

GIF demo

See all demos

Sample code

<script>
    import * as yup from 'yup';
    import {Form, Message} from 'svelte-yup';
    let schema = yup.object().shape({
        name: yup.string().required().max(30).label("Name"),
        email: yup.string().required().email().label("Email address"),
    });
    let fields = {email: "", name: ""};
    let submitted = false;
    let isValid;
    function formSubmit(){
        submitted = true;
        isValid = schema.isValidSync(fields);
        if(isValid){
            alert('Everything is validated!');
        }
    }
</script>

<Form class="form" {schema} {fields} submitHandler={formSubmit} {submitted}>
    <input type="text" bind:value={fields.name} placeholder="Name">
    <Message name="name" />
    <input type="text" bind:value={fields.email} placeholder="Email address">
    <Message name="email" />
    <button type="submit">Submit</button>
</Form>


Add isInvalid for making input border style.

Example:

<script>
...
import {Message, isInvalid} from 'svelte-yup';
...
$: invalid = (name)=>{
    if(submitted){
        return isInvalid(schema, name, fields);
    }
    return false;
}
...
</script>

<input type="text" class:invalid={invalid("name")} bind:value={fields.name} placeholder="Name">
<style>
.invalid {
    border-color: red !important;
}
</style>

All messages in one place

Example below to put all messages in one place by AllMessages component.

import {AllMessages} from 'svelte-yup';
<AllMessages />

Custom Message color

<Form ... color="#b00020">

Components

namepropsdescription
Formschema, fields, submitHandler, submitted and color
MessagenameError message of a field name by name prop. name should be the schema field name (no label name)
AllMessagesPuts all field messages in one place

Functions

isInvalid(schema:Object, name:String, fields:Object)

Example disable button until everything is validated

...
let btnDisabled = false;
$: if(submitted){
    btnDisabled = true;
    isValid = schema.isValidSync(fields);
    if(isValid){
        btnDisabled = false;
    }
}
...
<button type="submit" disabled={btnDisabled}>Submit</button>

Examples with source code

Author

Kamyar Lajani

License

MIT

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial