@validify-js/react
TypeScript icon, indicating that this package has built-in type declarations

1.4.1 • Public • Published

@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: "farid@example.com",
  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: "farid@example.com",
    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

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
1.4.10latest

Version History

VersionDownloads (Last 7 Days)Published
1.4.10
1.4.00
1.3.9-alpha0
1.3.8-alpha0
1.3.70
1.3.60
1.3.50
1.3.40
1.3.30
1.3.20
1.3.10
1.3.00
1.2.90
1.2.80
1.2.70
1.2.60
1.2.50
1.2.40
1.2.30
1.2.20
1.2.10
1.2.00
1.1.90
1.1.80
1.1.70
1.1.60
1.1.50
1.1.41
1.1.30
1.1.20
1.1.10
1.1.00
1.0.90
1.0.80
1.0.70
1.0.60
1.0.50
1.0.40
1.0.30
1.0.00

Package Sidebar

Install

npm i @validify-js/react

Weekly Downloads

1

Version

1.4.1

License

ISC

Unpacked Size

20.1 kB

Total Files

13

Last publish

Collaborators

  • faridmansimli