Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/vlazh/valtors

JavaScript Validation Library
https://github.com/vlazh/valtors

class decorators form form-validation forms javascript react typescript validation validation-library

Last synced: 2 months ago
JSON representation

JavaScript Validation Library

Awesome Lists containing this project

README

        

# Valtors [![npm package](https://img.shields.io/npm/v/valtors.svg?style=flat-square)](https://www.npmjs.org/package/valtors)

**Valtors** is a small flexible and extensible validation library for TypeScript/JavaScript. It provides [decorators](https://github.com/tc39/proposal-decorators) for classes and properties. Perfect worked with [MobX](https://mobx.js.org/).

Class decorator `@validatable` injects method `validate(propName?: keyof this)` and property with validation errors (default is `validationErrors`) which will available after `validate` method will be called.

## React + MobX + Valtors Example

```jsx
// Store for react component

import { action, observable } from 'mobx';
import { email, required, validatable } from 'valtors';

// @validatable without arguments injects `validationErrors` property for validation errors
@validatable('errors')
export default class AuthCredentialsStore {
@observable
@required()
@email()
username;

@observable
@required('Password is required')
password;

@action
submit() {
// Validate all fields.
if (!this.validate()) return;
// If store is valid submit.
}
}

// React component

import React, { useCallback } from 'react';
import { action } from 'mobx';
import { observer } from 'mobx-react-lite';
import styles from './SignIn.css';

function SignIn({ store }) {
const onSubmit = useCallback(action((e) => {
e.preventDefault();
store.submit();
}), [store]);

const onChange = useCallback(action(({ target: { name, value } }) => {
store[name] = value;
store.validate(name); // Validate only one field.
}), [store]);

const { errors } = store;

return (


{errors.username.error}


{errors.password.error}

Login

);
}

export default observer(SignIn);
```

## License

[MIT](https://opensource.org/licenses/mit-license.php)