2.6.1 • Published 6 months ago

valtors v2.6.1

Weekly downloads
26
License
MIT
Repository
github
Last release
6 months ago

Valtors npm package

Valtors is a small flexible and extensible validation library for TypeScript/JavaScript. It provides decorators for classes and properties. Perfect worked with MobX.

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

// 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 (
    <form onSubmit={onSubmit} noValidate>
      <input value={store.username} onChange={onChange} name="username" type="email" placeholder="email">
      <span className={errors.username.error ? styles['error'] : styles['hide']}>{errors.username.error}</span>

      <input value={store.password} onChange={onChange} name="password" type="password" placeholder="password">
      <span className={errors.password.error ? styles['error'] : styles['hide']}>{errors.password.error}</span>

      <button className={styles['btn-login']} type="submit">Login</button>
    </form>
  );
}

export default observer(SignIn);

License

MIT

2.6.1

6 months ago

2.6.0

6 months ago

2.5.2

11 months ago

2.5.3

9 months ago

2.5.0

1 year ago

2.5.1

1 year ago

2.4.1

2 years ago

2.4.0

2 years ago

2.3.2

3 years ago

2.3.1

4 years ago

2.3.0

4 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.0

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.6.0

5 years ago

1.5.0

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.0

6 years ago

1.2.0

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago

0.2.2

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.4

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.0

7 years ago