0.0.2 • Published 5 months ago

guardzilla v0.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

FormGuardJs Class Documentation

This is a comprehensive guide to the FormGuardJs class, inspired by Laravel’s Validation but tailored for JavaScript applications. The class provides a rich set of validation rules and supports custom validation callbacks.

Table of Contents

Introduction

The FormGuard class allows you to validate form data based on a variety of built-in rules. You can define your validation rules, custom error messages, and attributes that map to human-readable names for your fields.

Installation

You can install the FormGuard in your project by including the FormGuard class in your JavaScript/TypeScript application.

Usage

Basic Examples

Here’s a simple example that validates the name and age fields with basic rules:

const rules = {
    name: 'required|min:5',
    age: 'required|integer',
};

const messages = {
    nameRequired: 'Name is required',
    nameMin: 'Minimum value is :min',
    ageRequired: 'Age is required',
    ageInteger: 'Age value is not an integer',
};

const attributes = {
    name: 'Full Name',
    age: 'Age',
};

FormGuard.make(rules, messages, attributes);
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Rules as Array

You can also pass validation rules as an array:

const rules = {
    name: ['required', 'min:5'],
    age: ['required', 'integer'],
};

FormGuard.make(rules, messages, attributes)
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Rules as Object

If you prefer, you can define your validation rules as objects:

const rules = {
    name: { required: true, min: [5] },
    age: { required: true, integer: true },
};

FormGuard.make(rules, messages, attributes)
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Custom Rule Callbacks

Define Custom Callbacks

FormGuard.add('exists', ({value, fails}) => {
    if (!value) {
        fails('Name already exists');
    }
});
FormGuard.add('exists', ({value, fails}) => {
    return value !== false;
});

Definine Custom Callbacks with options

FormGuard.add({
    exists: {
        fn: ({value, fails}) => value,
        message: 'Name already exists'
    },

    // Add more custom Rules
});

Defining custom Rules globally

go to ./core/config.js, inside customRules define the rules like

{
    customRules: {
        ruleName: {
            fn: () => {}, // Define the callback here
            message: 'Custom Message'
        }
    }
}
FormGuard.exists = ({ value, fails }) => {
    if (!value) {
        fails('Name already exists');
    }
};

You can use custom validation callbacks as part of the rules:

// Usages of custom callbacks
const rules1 = {
    name: ['required', 'min:5', FormGuard.exists],
    age: 'required|integer',
};

// or as an item in an array 

const rules2 = {
    name: ['required', 'min:5', 'exists'],
    age: 'required|integer',
};

// or as a string:

const rules3 = {
    name: 'required|min:5|exists',
    age: 'required|integer',
};


FormGuard.make(rules1, messages, attributes).then().catch();
FormGuard.make(rules2, messages, attributes).then().catch();
FormGuard.make(rules3, messages, attributes).then().catch();
    

Or you can define an inline function as a callback:

const rules = {
    name: ['required', 'min:5', ({ value, fails }) => {
        if (!value) {
            fails('Name already exists');
        }
    }],
    age: 'required|integer',
};

FormGuard.make(rules, messages, attributes);
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Validation Rules Reference

Required Rules

RuleDescription
requiredThe field must not be empty.
required_if:field,valueThe field is required if another field has a specific value.
required_unless:field,valueThe field is required unless another field has a specific value.
required_with:fieldsThe field is required if any of the specified fields are present.
required_with_all:fieldsThe field is required if all of the specified fields are present.
required_without:fieldsThe field is required if any of the specified fields are not present.
required_without_all:fieldsThe field is required if none of the specified fields are present.

Data Type Rules

RuleDescription
numericThe field must be a number.
stringThe field must be a string.
integerThe field must be an integer.
arrayThe field must be an array.
fileThe field must be a valid file.
filesThe field must contain multiple files.
jsonThe field must be a valid JSON string.
booleanThe field must be either true or false.
dateThe field must be a valid date.
emailThe field must be a valid email address.
urlThe field must be a valid URL.
ipThe field must be a valid IP address.
uuidThe field must be a valid UUID.

String Formatting Rules

RuleDescription
trimThe field's value will be trimmed of whitespace.
capitalize:scopeThe field's value will be capitalized if scope is not provided. Set all scope to capitalize all the value. Set none scope to uncapitalize all the value
lowercaseThe field's value must be lowercase.
uppercaseThe field's value must be uppercase.
alphaThe field must contain only alphabetic characters.
alpha_numThe field must contain only letters and numbers.
alpha_dashThe field must contain letters, numbers, dashes, and underscores.
alpha_spacesThe field must contain only letters and spaces.
digits:valueThe field must have exactly the specified number of digits.
mimes:typesThe file must match one of the given MIME types.

Special Rules

RuleDescription
acceptedThe field must be accepted (for checkboxes).
confirmedThe field must have a matching *_confirmation field.
credit_cardThe field must be a valid credit card number.
contains:substringThe field must contain a specific substring.
not_contains:valueThe field's value must not contain the specified value.
in:valuesThe field must be included in the given list of values.
not_in:valuesThe field's value must not be in the given list of values.
existsThe field must pass a custom existence check (see callbacks).
pattern:regexThe field's value must match the specified regex pattern.

Comparison Rules

RuleDescription
min:valueThe field's value must be at least the specified minimum.
max:valueThe field's value must not exceed the specified maximum.
between:min,maxThe field's value must be between min and max.
same:otherfieldThe field's value must match another field's value.
gt:fieldThe field must be greater than the specified field.
gte:fieldThe field must be greater than or equal to the specified field.
lt:fieldThe field must be less than the specified field.
lte:fieldThe field must be less than or equal to the specified field.
range:min,maxThe field's value must be within the given range.

Miscellaneous Rules

RuleDescription
filledThe field must have a value, even if empty.
nullableThe field can be null.
active_urlThe field must be a valid active URL.
imageThe file must be an image.
audioThe file must be an audio file.
videoThe file must be a video file.
pattern:regexThe field's value must match the specified regex pattern.

Custom Messages

You can customize error messages using the messages parameter when creating a new FormGuard instance. Messages can use placeholders like :attribute, :min, or :max to dynamically insert values.

const messages = {
    nameRequired: 'Name is required',
    nameMin: 'Name must be at least :min characters',
    ageRequired: 'Age is required',
    ageInteger: 'Age must be an integer',
};

Custom Attributes

You can customize attribute names for friendlier error messages by passing an attributes object:

const attributes = {
    name: 'Full Name',
    age: 'Age',
};

This allows the error messages to display Full Name instead of name.

Custom Callbacks

Registering a Custom Rule

You can register custom validation rules using functions. Here's an example of creating and using a custom validation rule:

FormGuard.exists = ({ value, fails }) => {
    if (!value) {
        fails('This value does not exist.');
    }
};

const rules = {
    name: ['required', 'exists'],
};

FormGuard.make(rules, messages, attributes)
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Inline Callback Example

You can also provide inline custom rules as callbacks:

const rules = {
    name: ['required', ({ value, fails }) => {
        if (value !== 'allowed_name') {
            fails('This name is not allowed.');
        }
    }],
};

FormGuard.make(rules, messages, attributes)
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Or you can define an inline function as a callback:

const rules = {
    name: ['required', 'min:5', ({ value, fails }) => {
        if (!value) {
            fails('Name already exists');
        }
    }],
    age: 'required|integer',
};

FormGuard.make(rules, messages, attributes)
    .then(({ validated, formData }) => {
        // Handle success
    })
    .catch(error => {
        console.error(error);
    });

Using defineForm To Validate Form

FormGuard.defineForm(
    formSelector,
    rules,
    messages,
    attributes
);

Usage:

    <!--index.html-->
    <html>
        <head>
            ...
            <script src="http://npmpackagelist.org/formguard.js"></script>

        </head>
        <body>

            <form method="POST" action="/api/login" id="signup-form">
                <input type="text" name="email"/>
                <input type="text" name="first_name"/>
                <input type="text" name="last_name"/>
                <input type="text" name="username"/>
                <input type="password" name="password"/>
                <input type="password" name="password_confirmation"/>
                <button type="submit">Sign Up</button>
            </form>

        </body>
        <script src="./index.js"></script>
    </html>
// index.js
const rules = {
    email: 'required|email',
    first_name: 'required|alpha',
    last_name: 'required|alpha',
    password: 'required|password|confirmed'
};

const messages = {
    emailRequired: 'Email Address is required',
    first_nameRequired: ':attribute is requred',
};

const attributes = {
    first_name: 'First Name',
    last_name: 'Last Name',
};


const validator = FormGuard.defineForm(
    'signup-form',
    rules,
    messages,
    attributes
);

validator
.on('submitted', (response, {setAuth}) => {
    setAuth(response.token);
})
.on('submit', ({validated, formData}) => {

})