npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mobx-validated-field

v5.1.0-alpha.2

Published

This library provides an extensible ValidatedField class whose properties are all made observable using mobx.

Downloads

136

Readme

Mobx ValidatedField

This library provides an extensible ValidatedField class whose properties are all made observable using mobx.

Usage

import { ValidatedField } from './ValidatedField';
  
// instantiate
const nameField = new ValidatedField();
  
// add validators
nameField.addValidators([
    {
        id: 'fieldIsNotEmpty', // used to keep track of the failing validation
        defaultMessage: 'this field cannot be empty', // message to return when a validation fails
        validateOnChange: (val: string) => {
            // callback that runs on every change
            // returning false indicates an error
            // you can also return a string that will indicate an error and 
            // override the defaultMessage
            // this callback is not required
        },
        validateOnSubmit: (val: string) => {
            // same as validateOnChange but runs when the field is submitted as opposed to every change
            // allows for a final validation of the field
            if (val === '') return false;
        }
    }
]);

ValidatedField Class

interface IValidatedField {
    new (config: IValidatedFieldConfig): IValidatedField;
    value: string;
    hasError: boolean;
    isPristine: boolean;
    isDirty: boolean;
    isMaybeValid: boolean;
    isValid: boolean;
    wasSubmitted: boolean;
    errors: IFieldValidator[];
    validators: IFieldValidator[];
    addValidators(configs: IValidatorConfig[]): void;
    handleChange(val: string): void;
    handleSubmit(): void;
}

Constructor

The constructor accepts a config object. See the ValidatedFieldConfig section to see the available options.

Member Descriptions

addValidators(config: IValidatorConfig[]): void

method for adding validators to the field. Each config is used to instantiate a FieldValidator instance. A list of these validators is accessible at ValidatedField#validators

value: string

The current value of the field.

hasError: boolean

True when any of the validators failed. This is not necessarily the opposite of isValid since an error could occur before the field is submitted.

isPristine: boolean

True when the field has not yet changed. ie handleChange has not been called.

isDirty: boolean

True when the field has changed. ie handleChange has been called.

isMaybeValid: boolean

True when all validators are either maybeValid or valid

isValid: boolean

True when all validators are valid and field has been submitted.

wasSubmitted: boolean

Only true after handleSubmit was called.

errors: IFieldValidator[]

returns a list of all validators that have errors.

validators: IFieldValidator[]

returns a list of all validators.

handleChange(val: string): void

Should be called any time the value of the field changes. Invokes the validateOnChange callback on each validator.

handleSubmit(): void

Should be called when the field is done being edited. Invokes the validateOnSubmit callback on each validator.

ValidatedField Config

You can pass a config object to the ValidatedField constructor function. Here are the available options.

interface IValidatedFieldConfig {
    placeholder?: string;
    trimOnSubmit?: boolean;
    required?: boolean;
}

Property Descriptions

placeholder: string

Provide a placeholder value for the field. This doesn't do anything special, but the passed value is available at fieldInstance.placeholder. Defaults to undefined.

trimOnSubmit: boolean

Trim the value before invoking the validateOnSubmit callback. Defaults to false.

required: boolean

Setting this to true adds a validator which validates that the field's value is set on submit. Defaults to false.

Example Using Config

import { ValidatedField } from './ValidatedField';
  
// instantiate
const trimmedField = new ValidatedField({trimOnSubmit: true});
  
// add validators
trimmedField.addValidators([
    {
        id: 'fieldIsNotEmpty', // used to keep track of the failing validation
        defaultMessage: 'this field is required', // message to return when a validation fails
        validateOnSubmit: (val: string) => {
            // same as validateOnChange but runs when the field is submitted as opposed to every change
            // allows for a final validation of the field
            if (val === '') return false;
        }
    }
]);

FieldValidator Config

Config that is passed to ValidatedField#addValidators

interface IValidatorConfig {
    id: string;
    defaultMessage: string;
    validateOnChange?: (val: string) => boolean | string;
    validateOnSubmit?: (val: string) => boolean | string;
}

Property Descriptions

id: string

Unique id for the validation. Can be used to determine which validation is failing.

defaultMessage: string

The message that is returned when a validation callback has failed. ie returned false

validateOnChange: (val: string) => void

Callback that runs on every change. Returning false indicates a validation error. You can also return a string that will indicate and error and override the defaultMessage

validateOnSubmit: (val: string) => void

same as validateOnChange but runs when the field is submitted as opposed to every change. This allows for a final validation on the value the user wants to submit.

FieldValidator Class

interface IFieldValidator {
    id: string;
    isMaybeValid: boolean;
    isValid: boolean;
    hasError: boolean;
    error: string;
    handleChange(val: string): void; // used internally, should not be called by user
    handleSubmit(val: string): void; // used internally, should not be called by user
}

Member Descriptions

id: string

Unique id for the validation. Can be used to determine which validation is failing.

isMaybeValid: boolean

True when validation has passed.

isValid: boolean

True when the validation passes on validatedOnSubmit

hasError: boolean

True when either a validateOnChange or validateOnSumbit validation fails

error: string

The actual error message when hasError is true, null if not

Using with React

This library was intended for use with React and Mobx. Here's a simple example implementing it.

// TODO: add this.

Extending the class

You could also extend the ValidatedField class if you wanted to add additional custom functionality.

import { ValidatedField } from './ValidatedField';
  
export class MyValidatedField extends ValidatedField {
    
    constructor() {
        super();
        this.addValidators([
            {
                id: 'not empty',
                defaultMessage: 'this field cannot be empty',
                validateOnSubmit: (val: string) => {
                    if (val === '') return false;
                },
            },
        ]);
    }
}
  
const myField = new MyValidatedField();
  
myField.handleChange('stuff');
myField.handleSubmit();
  
console.log(myField.isValid); // true