Giter Club home page Giter Club logo

whyvra.blazor.forms's Introduction

Whyvra.Blazor.Forms

NuGet Package NuGet Package Download Count LICENSE PRs Welcome

A dynamic form builder that binds to your model classes and creates the corresponding HTML form for you.

Introduction

Create dynamic forms with the generic FormBuilder<T> class and then get a FormModel<T> by calling the Build() method on the form builder. The form model can then be passed to a FormRenderer which will output the HTML markup for your form.

This could be used to create renderers for different frameworks. However, given the current state of Blazor and how most frameworks depend on JavaScript, only a renderer for the Bulma framework has been created.

Bulma is a CSS-only framework that does not require any external JavaScript. For this reason, it integrates well with Blazor.

Installation

dotnet add package Whyvra.Blazor.Forms

In your Blazor project, add reference to the Bulma CSS to your wwwroot/index.html:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">

You can also add the Font Awesome icons, if you intend to use them (or any other glyphs like Material Design Icons).

<script defer src="https://use.fontawesome.com/releases/v5.14.0/js/all.js"></script>

You can also find some alternative themes for Bulma here.

Usage

Given the following model class:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

The generic FormBuilder<T> class can be used to define elements on a form. The resulting FormModel can then be used a FormRenderer to generate the corresponding HTML <form>.

@using System.Text.Json
@using Whyvra.Blazor.Forms
@using Whyvra.Blazor.Forms.Renderers

<BulmaForm FormModel="formModel" FormState="FormState.New">
</BulmaForm>

<button class="button is-success" @onclick="ProcessForm">Done</button>

@code
{
  private FormModel<Contact> formModel;

  protected override void OnInitialized()
  {
    formModel = new FormBuilder<Contact>()
      .Input(x => x.FirstName)
      .Input(x => x.LastName)
      .Input(x => x.Email)
      .Build();
  }

  private void ProcessForm()
  {
    var model = formModel.DataModel;
    Console.WriteLine(JsonSerializer.Serialize(model));
  }
}

Form Validation

In order to validate the form, you can supply pass a Func<string, IEnumerable<string>> parameter called GetValidationMessages to the FormRenderer. The provided function should return a list of error messages for the PropertyName that gets passed.

Given the following validator for the Contact model class :

public class ContactValidator : AbstractValidator<Contact>
{
    public ContactValidator()
    {
        RuleFor(x => x.FirstName).NotNull().NotEmpty().MaximumLength(32);
        RuleFor(x => x.LastName).NotNull().NotEmpty().MaximumLength(32);
        RuleFor(x => x.Email).EmailAddress();
    }
}

The ValidateProperty function that will return a list of error messages for each property matching the given key. This function can be passed as the GetValidationMessages paramter on the BulmaForm razor component.

@using System.Text.Json
@using FluentValidation
@using Whyvra.Blazor.Forms
@using Whyvra.Blazor.Forms.Renderers

@inject IValidator<Contact> Validator

<BulmaForm @ref="form" FormModel="formModel" FormState="FormState.New" GetValidationMessages="ValidateProperty">
</BulmaForm>

<button class="button is-success" @onclick="ProcessForm">Done</button>

@code
{
  private IFormRenderer form;
  private FormModel<Contact> formModel;

  protected override void OnInitialized()
  {
    formModel = new FormBuilder<Contact>()
      .Input(x => x.FirstName)
      .Input(x => x.LastName)
      .Input(x => x.Email)
      .Build();
  }

  private void ProcessForm()
  {
    var model = formModel.DataModel;
    var result = Validator.Validate(model);

    if (result.IsValid)
    {
      Console.WriteLine(JsonSerializer.Serialize(model));
    }
    else
    {
      // Trigger validation on whole form
      form.ValidateForm();
    }
  }

  private IEnumerable<string> ValidateProperty(string key)
  {
    var result = Validator.Validate(formModel.DataModel);

    return result.Errors
        .Where(x => x.PropertyName.Equals(key))
        .Select(x => x.ErrorMessage);
  }
}

License

Released under the MIT License.

whyvra.blazor.forms's People

Contributors

whyvra avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.