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

carbon-form

v1.0.13

Published

Forms to be used with the CarbonJS Framework or standalone

Downloads

34

Readme

CarbonJS Forms / carbon-form

The carbon-form module provides easy-to-use forms in your projects. It is a complete solution which not only provides rendering but filtering and validation too. It packs all the logic behind HTML forms and it abstracts a lot of work so that you can focus on building awesome web applications and best of all it allows you to define the layout and style your forms any way you want them.

If you have ever used Zend_Form before you're going to be familiar with the syntax and if not just keep reading.

Installation

npm install carbon-form [--save]

Usage

The usage is pretty simple. You create a form and then add elements to it. For each element you define a set of options such as name, label, filters, validators, HTML attributes etc. The following example should present most of carbon-form features.

Defining the form (file: signup-form.js)

First you need to define your form and elements that it will contain.

var Form = require("carbon-form");
var Filter = require("carbon-filter");
var Validate = require("carbon-validate");

module.exports = exports = function(options) {
    var form = new Form(options);

    form.setAction("/signup");
    form.setViewScriptFile("forms/signup.jade");

    form.addElements([
        new Form.Element.Text("name", {
            label: "Name",
            attribs: {
                class: "text-field"
            },
            filters: [
                new Filter.StringTrim()
            ],
            validators: [
                new Validate.NotEmpty({
                    messages: {
                        "is_empty": "Name is required"
                });
            ]
        }),
        new Form.Element.Text("email_address", {
            label: "Email address",
            attribs: {
                class: "text-field"
            },
            filters: [
                new Filter.StringTrim()
            ],
            validators: [
                new Validate.NotEmpty({
                    messages: {
                        "is_empty": "Email address is required"
                    }
                }),
                new Validate.StringLength({
                    max: 255,
                    messages: {
                        "too_long": "Email address can't be longer than %max% characters"
                    }
                }),
                new Validate.EmailAddress(),
                new Validate.DbNoRecordExists({
                    adapter: "mongoose",
                    collection: "users",
                    field: "email_address",
                    messages: {
                        "record_found": "Email address is already in the database"
                    }
                })
            ]
        }),
        new Form.Element.Password("password1", {
            label: "Password",
            attribs: {
                class: "text-field"
            },
            validators: [
                new Validate.NotEmpty({
                    messages: {
                        "is_empty": "Password is required"
                    }
                }),
                new Validate.StringLength({
                    min: 6,
                    messages: {
                        too_short: "Password must be at least %min% characters long"
                    }
                })
            ]
        }),
        new Form.Element.Password("password2", {
            label: "Repeat password",
            attribs: {
                class: "form-control"
            },
            validators: [
                new Validate.NotEmpty({
                    messages: {
                        "is_empty": "Repeated password is required"
                    }
                }),
                new Validate.Identical({
                    token: "password1",
                    messages: {
                        "not_same": "Passwords do not match"
                    }
                })
            ]
        }),
        new Form.Element.Button("submit", {
            content: "Sign up",
            attribs: {
                class: "btn btn-red",
                type: "submit"
            }
        })
    ]);

    return form;
}

Defining form layout (file: signup-form.jade)

Since carbon-form gives you freedom to style your own forms any way you wish, you can define form layout in the separate file and then tell to carbon-form where to look for this file. When the form renders it will use this layout as a template.

.form-group
    div
        label(for="#{elements.name.getName()}")
            != elements.name.getLabel()
    div
        != elements.name.render()  
.form-group
    div
        label(for="#{elements.email_address.getName()}")
            != elements.email_address.getLabel()
    div
        != elements.email_address.render()  
.form-group
    div
        label(for="#{elements.password1.getName()}")
            != elements.password1.getLabel()
    div
        != elements.password1.render()  
.form-group
    div
        label(for="#{elements.password2.getName()}")
            != elements.password2.getLabel()
    div
        != elements.password2.render()  
.form-group
    div
        != elements.submit.render()    

Validation and rendering (using carbon-framework)

This example features carbon-framework just to make it easier for you to understand how carbon-form works in reality. Of course you can use carbon-form with any other Node.js framework or no framework at all.

module.exports = function() {
    return {
    	signupAction: {
            post: function(req, res) {
                var postData = req.body;

                var form = require("./forms/signup-form")({
                    viewiewScriptPaths: res.viewPaths
                });

                form.isValid(postData, function(err, values) {
                    if (err)
                    {
                        form.render(function(err) {
                            // Now in the view all you have to do is call `!= form.render()`
                            // (if you're using Jade engine) and it will return rendered form
                            // as HTML all together with all errored fields

                            res.render("scripts/signup", {
                                formSignup: form
                            });
                        });
                    }
                    else
                    {
                        // Form validation is successful and argument `values` now contains all
                        // field values which are filtered and validated and therefor safe
                        // to be inserted into the database

                        res.redirect("/signup-success");
                    }
                });

            }
    	}
    }
}

Elements

The carbon-form currently supports 6 HTML form elements (Button, Checkbox, Hidden, Password, Text, Textarea) and 4 extended elements (EmailAddress, Link, Recaptcha, Switch).

Subforms

Depending on how you organize your forms you can nest one or more forms within a single form.

var Form = require("carbon-form");

var form = new Form();
var buttons = new Form();

parentForm.addSubForm("buttons", buttons);

Contributing

If you're willing to contribute to this project feel free to report issues, send pull request, write tests or simply contact me - Amir Ahmetovic

Licence

This software is available under the following licenses:

  • MIT