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

@validify-js/react

v1.4.1

Published

validation package for React.js and React Native

Downloads

10

Readme

@validify-js/core

npm version   npm downloads/month   GitHub license


installation

npm install --save @validify-js/react

please, buy me a coffe to support this package.

buy me a coffee

Table of contents

  1. Creating Schema
  2. Validating an object
  3. Using with React.js
  4. With initial values
  5. Dependent fields (dynamic schema)
  6. Using with React-native
  7. Keep in mind (important!)

Creating Schema

an example of how to create a valid schema

// keep in mind that "type" property must be specified!!!
// for example type:Number

import { Schema } from "@validify-js/react";

export const user = new Schema({
  name: { type: String, required: false, minLength: 7 },
  email: { type: String, required: true, email: true },
  gender: { type: String, required: true },
  hobbies: {
    type: Array,
    required: true,
    minLength: 3,
    message: "3 hobbies should be selected at least!", // if you omit  the "message" field, default message will be displayed
  },
  blocked: {
    type: Boolean,
    required: false,
  },
  password: {
    type: String,
    required: true,
    pattern: /[A-Za-z0-9]{8,}/,
  },
  age: {
    type: Number,
    required: false,
    min: 18,
    max: 30,
  },
  profession: {
    type: String,
    required: true,
  },
});

Validating an object

you can validate any object or jsx form by using the schema wich we created above. for example:

const user = {
  name: "Farid",
  email: "[email protected]",
  hobbies: ["sky-diving", "soccer"],
  age: 25,
};

const { ok, data, errors } = userSchema.validate(user);

// validation will be failed. (ok --> false),
// because, a few fields are required in the above schema.

Using with React.js

how to use it with React.js ? that's amazingly easy

// best practice! create the schema as a seperate file
// and import it to keep code clean.

import React from "react";
import { useSchema, Schema } from "@validify-js/react";

// create a schema ....
// we are going to use the same schema which we created above.

const ProfilePage = (props) => {
  const form = useSchema(userSchema);

  const { name, age, profession, blocked, hobbies, gender } = form.data;

  // you can destructure the fields from form.data, if you want

  const submitHanlder = (event) => {
    event.preventDefault();

    const { ok, data, errors } = form.validate();

    if (ok) {
      // if "ok" is true, it means form is valid , you are good to go!
      // "data" includes input values
      // "errors" includes the error messages of invalid fields, if exists
    }
  };

  return (
    <div className="App">
      <div>
        <form onSubmit={submitHanlder} onReset={form.resetForm}>
          <input
            type="text"
            name="name"
            onChange={form.updateField}
            onBlur={form.blurField}
            value={name.value}
          />
          <br />
          <small>{name.error}</small>
          <br />
          <input
            type="number"
            name="age"
            onChange={form.updateField}
            onBlur={form.blurField}
            value={age.value}
          />
          <br />
          {age.touched && <small>{age.error}</small>}
          <br />
          <div>
            {hobbieList.map((hobbie, index) => (
              <div key={index}>
                <label htmlFor={`hobbie${index}`}>{hobbie}</label>
                <input
                  id={`hobbie${index}`}
                  type="checkbox"
                  name="hobbies"
                  value={hobbie}
                  onChange={form.updateList}
                  onBlur={form.blurList}
                  checked={hobbies.value.includes(hobbie)}
                />
              </div>
            ))}
          </div>
          <br />
          <small>{hobbies.error}</small>

          <hr />
          <input
            type="checkbox"
            name="blocked"
            onChange={form.updateField}
            onBlur={form.blurField}
            checked={blocked.value}
          />
          <br />
          <small>{blocked.error}</small>
          <hr />
          <input
            type="radio"
            name="gender"
            value="male"
            onChange={form.updateField}
            checked={gender.value === "male"}
            onBlur={form.blurField}
          />
          <input
            type="radio"
            value="female"
            name="gender"
            onChange={form.updateField}
            checked={gender.value === "female"}
            onBlur={form.blurField}
          />
          <br />
          <small>{gender.error}</small>
          <hr />
          <select
            name="profession"
            onChange={form.updateField}
            defaultValue={profession.value || "default"}
          >
            <option value="default" disabled>
              select profession
            </option>
            {professionList.map((profession, key) => (
              <option key={key} value={profession}>
                {profession}
              </option>
            ))}
          </select>
          <br />
          <small>{profession.error}</small>
          <hr />
          <button type="submit">submit</button>
          <button type="reset">reset</button>
        </form>
      </div>
    </div>
  );
};

export default ProfilePage;

KEEP IN MIND:   

  • name attribute of the input should match with the exact property in schema

  • we'are using "updateList" method for multiple(array) values instead of "updateField"

  • we'are also using "blurList" method for multiple(array) values instead of "blurField"

look at the --> (hobbies) in the jsx above ^


you might not belive, however, that's pretty much it, as simple as you see

With initial values

how to use it with initial values ? this is also amazingly easy

// best practice! create the schema as a seperate file
// and import it to keep code clean.

import React from "react";
import { useSchema } from "@validify-js/react";

import { personSchema } from "../validations/person";


const  ProfilePage = (props) => {

  const form = useSchema(personSchema, {
    name: "Farid",
    email: "[email protected]",
    age: 20,
  });

  // or you can also use it like below:

  // const form = useSchema(personSchema,props.user);

  ....
  ....

Dependent fields (dynamic schema)

how to use dependent fields ? don't worry, it's a piece of cake

  • use the useDynamic hook instead of useSchema

  • just create a schema and specify dependent fields inside the hook.

// best practice! create the schema as a seperate file
// and import it to keep code clean.

import React from "react";
import { useDynamic } from "@validify-js/react";

const ProfilePage = (props) => {

  const form = useDynamic(userSchema,
      (data) => {
        return {
          password: {
            required: data.name ? true : false,
          },
          age: {
            required: data.email ? true : false,
            min: data.email ? 25 : 18
          }
        };
      },
      ["name", "email"]
    );

Using with React-native

// just pass the name of the field to the function, that's it.

<TextInput
  onChangeText={form.updateField("username")}
  onBlur={form.blurField("username")}
  value={form.data.username.value}
/>;

<Text>{form.data.username.error}</Text>;

Keep in mind

  • name attribute of the input should match with the exact property in schema (important!)

  • "type" property must be specified in the Schema

  • name attribute of the input should match with the exact property in schema

  • we'are using "updateList" method for multiple (array) values instead of "updateField"

  • we'are also using "blurList" method for multiple (array) values instead of "blurField"

that's pretty much it, guys!


you can reach me here:


Linkedin    |    Facebook    |    Twitter    |    Instagram


please, buy me a coffe to support this package.

buy me a coffee