• Stars
    star
    224
  • Rank 176,962 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A client validation library for ASP.NET MVC that does not require jQuery

ASP.NET Client Validation

Enables ASP.NET MVC client-side validation without jQuery! Originally forked from https://github.com/ryanelian/aspnet-validation. This library replaces the need for jquery.validate.min.js, jquery.validate.unobtrusive.min.js. It's a nearly drop-in replacement. The only difference is you need to initialize the library as shown in the Quickstart Guide.

npm Build Status

Install

npm install aspnet-client-validation

or

yarn add aspnet-client-validation

Alternatively, extract these files from the dist.zip folder of the latest release:

  • aspnet-validation.min.js
  • aspnet-validation.min.js.map

aspnet-client-validation uses Promise API, which is not supported in Internet Explorer. It is recommended to use promise-polyfill or ts-polyfill or core-js to resolve this issue...

If you are also using Bootstrap, you may un-jQuery the application by using https://github.com/thednp/bootstrap.native

Quick Start Guide

Via <script src="...">

<script src="promise-polyfill.min.js"></script>
<script src="aspnet-validation.min.js"></script>
// Exposes window['aspnetValidation']
var v = new aspnetValidation.ValidationService();
v.bootstrap();

Via CommonJS / Browserify

require('core-js');
const aspnetValidation = require('aspnet-client-validation');

let v = new aspnetValidation.ValidationService();
v.bootstrap();

Via TypeScript / ES Modules

import 'ts-polyfill';
import { ValidationService } from 'aspnet-client-validation';

let v = new ValidationService();
v.bootstrap();

Use instapack for easy, rapid, and painless web application front-end development using TypeScript!

Why?

jquery-3.3.2.min.js + jquery.validate.min.js + jquery.validate.unobtrusive.min.js = 112 KB

aspnet-validation.min.js: 10.6 KB (9.46%, ~4 KB GZIP)

  • promise-polyfill: +3.06 KB (< 1 KB GZIP)

Building the Source Code

git clone https://github.com/haacked/aspnet-client-validation.git
npm install
script/build   # If using PowerShell: script/build.ps1

Adding Custom Validation

Example stolen from https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation

Server Code (C#)

public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator
{
    private int _year;

    public ClassicMovieAttribute(int Year)
    {
        _year = Year;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        Movie movie = (Movie)validationContext.ObjectInstance;

        if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-classicmovie", GetErrorMessage());

        var year = _year.ToString(CultureInfo.InvariantCulture);
        MergeAttribute(context.Attributes, "data-val-classicmovie-year", year);
    }
}

Client Code

import { ValidationService } from 'aspnet-client-validation';
let v = new ValidationService();

v.addProvider('classicmovie', (value, element, params) => {
    if (!value) {
        // Let [Required] handle validation error for empty input...
        return true;
    }

    // Unlike the original, data-val-classicmovie-year is bound automatically to params['year'] as string!
    let year = parseInt(params.year);
    let date = new Date(value);
    let genre = (document.getElementById('Genre') as HTMLSelectElement).value;

    if (genre && genre === '0') {
        return date.getFullYear() <= year;
    }

    return true;
});

v.bootstrap();

Adding Custom Asynchronous Validation

Other than boolean and string, addProvider callback accepts Promise<string | boolean> as return value:

v.addProvider('io', (value, element, params) => {
    if (!value) {
        return true;
    }

    return async () => {
        let result: number = await Some_IO_Operation(value);
        return result > 0;
    };
});

Subscribing to Client Form Validation Event

const form = document.getElementById('form');
form.addEventListener('validation', function (e) {
    /* Check if form is valid here. */
});

Programatically validate a form

v.validateForm(document.getElementById('form'));

Checking form validity

v.isValid(document.getElementById('form'))

By default it will try to validate the form, before returning whether the form is valid. This can be disabled by setting the prevalidate parameter like so:

v.isValid(document.getElementById('form'), false)

You can also supply a callback function to be run after the check.

v.isValid(document.getElementById('form'), true, myCallbackFn)

Checking field validity

Similar to checking a forms validity, you can check individual fields too.

v.isFieldValid(document.getElementById('field'))

By default it will try to validate the form surrounding the field, before returning whether the field is valid. This can be disabled by setting the prevalidate parameter like so:

v.isFieldValid(document.getElementById('field'), false)

You can also supply a callback function to be run after the check.

v.isFieldValid(document.getElementById('field'), true, myCallbackFn)

Hidden fields validation

By default validation is skipped for hidden fields. To enable validation for hidden fields validation use:

v.allowHiddenFields = true;

Monitoring the DOM for changes

If configured, aspnet-client-validation can monitor the DOM for changes using MutationObserver, if the browser supports it. As new elements are added/modified, the library will automatically wire up validation directives found. This can be very useful when using frameworks that modify the DOM, such as Turbo. To configure this, set the watch option to true when calling bootstrap:

let v = new aspnetValidation.ValidationService();
v.bootstrap({ watch: true });

Logging

There is a rudimentary logging infrastructure in place if you want to get more insight into what the library is doing. To enable logging, pass an object that implements the Logger interface (see below) in to the ValidationService constructor. The window.console object satisfies this interface automatically:

// The Logger interface, for reference
export interface Logger {
    log(message: string, ...args: any[]): void;
    warn(message: string, ...args: any[]): void;
}

let v = new aspnetValidation.ValidationService(console);
v.bootstrap();

More Repositories

1

seegit

SeeGit - The Git Repository Visualizer
C#
508
star
2

CodeHaacks

This is a collection of prototypes, samples, proof-of-concepts. None of this is meant to be used in production code, but you can take any of the ideas you like and try them out in your own projects.
C#
311
star
3

routemagic

Utility Library to get the most out of ASP.NET Routing.
C#
186
star
4

haacked.com

You've been haacked and you like it
Shell
145
star
5

Rothko

An abstracted library for interacting with the file system, registry, etc.
HTML
81
star
6

Encourage

A bit of encouragment added to Visual Studio
C#
75
star
7

Subtext

Subtext Blog Engine
C#
65
star
8

AutoUpdate

A package that helps to build self-updating web applications using NuGet.
C#
64
star
9

dotfiles

My dotfiles and scripts I use on dev machines
Shell
52
star
10

ReallyEmptyMvc3ProjectTemplate

It's a really really empty MVC 3 project template
C#
50
star
11

mvc-metadata-conventions

Convention based approach to MVC Model Validation and Model Metadata
C#
43
star
12

aspnetmvc-action-checker

Drop in ASP.NET MVC Controller and Action that displays any actions that modify resources (HTTP POST, PUT, DELETE, and PATCH) that do not have an Authorize or ValidateAniForgeryToken attributes applied.
C#
39
star
13

jQuery-Live-Preview

A jQuery Plugin for previewing comments as HTML
JavaScript
31
star
14

NullGuard

An experiment in guarding against null arguments
C#
28
star
15

TimedLock

A Lock structure with timeout and stack traces in case of deadlock
C#
25
star
16

encourage-atom

An Atom extension that adds little encouragements while you work
JavaScript
24
star
17

jquery.undoable

This is a plugin that provides a more usable alternative to confirmation dialogs by assisting in building user interfaces which allow undoing operations.
JavaScript
20
star
18

gh-pages-demo

GitHub Pages Demonstration
Ruby
20
star
19

octokit-oauth-demo

A demo of using Octokit.net with the OAuth web flow
C#
18
star
20

ai-demo

Demo of Open AI with ASP.NET Core etc.
C#
13
star
21

haackbar

It's a trap! Jekyll theme for a great looking site. Used by haacked.com.
SCSS
12
star
22

encourage-mobile

A mobile app built with Xamarin to encourage people.
C#
9
star
23

simple-editable-div

A clean simple cross browser editable div
JavaScript
9
star
24

feedback

Ask @haacked anything!
7
star
25

HaackHub

Repo for a talk about C# 8.
C#
7
star
26

UpdatePanelExample

A simple update panel in asp.net core using Vanilla JS
C#
6
star
27

disqus-importer

Used to read a Disqus import file and generate Jekyll data for rendering comments
C#
5
star
28

NugetSignChecker

Checks the top twenty unique NuGet community packages for an author signature
C#
5
star
29

EmojiDownloader

Octokit example of downloading emojis
C#
4
star
30

jekyll-url-fixer

Used to fix my broken URLs
C#
4
star
31

TextWrapper

Just some crappy code I wrote to change a document to have a max column width
C#
4
star
32

aspire-efcore-postgres-demo

A simple demo of Aspire and EF Core with Postgres
C#
4
star
33

ConferenceSessionBrowser

JavaScript
3
star
34

subtext-jekyll-exporter

Some scripts to export Subtext to Jekyll
C#
3
star
35

moodswings

A package used to demonstrate NuGet PowerShell scripts.
PowerShell
2
star
36

fritz-demo

C#
2
star
37

fun-with-infinite-sums

Playing around with infinite series
C#
2
star
38

code.haacked.com

A repository for old code demos I need to migrate to proper repos
1
star
39

DemoRepo

1
star
40

Media

Various images, logos, icons, etc. associated with haacked.com and other stuff I work on
1
star
41

TerminalServicesPortChanger

Simple app to change your Terminal Services Port as described in http://haacked.com/archive/2006/10/16/Remote_Desktop_On_A_NonStandard_Port.aspx/#comment-3454189709
C#
1
star
42

demo.haacked.com

This site is a playground for me to host various demo code.
1
star
43

aboard-feedback

A public repository for feedback on https://getaboard.net/
1
star
44

haacked

All about me me me!
1
star
45

docker-efcore-postgres-demo

Example of an ASP.NET Core app connecting to postgrges running in a docker container using EF Core.
CSS
1
star