![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
aspnet-client-validation
Advanced tools
Enables ASP.NET MVC client-side validation, without jQuery!
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 install aspnet-client-validation
or
yarn add aspnet-client-validation
Alternatively, extract these files from the dist.zip folder of the latest release:
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
<script src="promise-polyfill.min.js"></script>
<script src="aspnet-validation.min.js"></script>
// Exposes window['aspnetValidation']
var v = new aspnetValidation.ValidationService();
v.bootstrap();
require('core-js');
const aspnetValidation = require('aspnet-client-validation');
let v = new aspnetValidation.ValidationService();
v.bootstrap();
import 'ts-polyfill';
import { ValidationService } from 'aspnet-client-validation';
let v = new ValidationService();
v.bootstrap();
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)
Also, jquery.validate.unobtrusive.min.js
has not been meaningfully updated in over a decade, and is hard to configure.
git clone https://github.com/haacked/aspnet-client-validation.git
npm install
script/build # If using PowerShell: script/build.ps1
Example stolen from https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation
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);
}
private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value) {
if (attributes.ContainsKey(key)) {
return false;
}
attributes.Add(key, value);
return true;
}
}
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();
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;
};
});
By default, validation occurs immediately upon changes to form fields: on input
for inputs and textareas, and on change
for selects.
One can change to a different event by setting a field's data-val-event
attribute. For example, one can use data-val-event="blur"
to validate that field on the blur
event.
To prevent unnecessary validation, a debounce of 300ms is used. This ensures validation does not occur for every keystroke, which is especially important during remote validation.
In some cases it may be unnecessary, for example when performing local validation on blur (rather than on change). To change the default:
v.debounce = 0;
const form = document.getElementById('form');
form.addEventListener('validation', function (e) {
/* Check if form is valid here. */
});
v.validateForm(document.getElementById('form'));
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)
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 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)
By default validation is skipped for hidden fields. To enable validation for hidden fields validation use:
v.allowHiddenFields = true;
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 });
Alternatively, to update the validation service for a specific form (which was created or modified dynamically) without using a MutationObserver
:
let form = document.getElementById('my-form');
v.scan(form);
One can customize the CSS classes so the generated markup is compatible with various frameworks. For example, to integrate with Bootstrap (v5+):
var v = new aspnetValidation.ValidationService();
v.ValidationInputCssClassName = 'is-invalid'; // change from default of 'input-validation-error'
v.ValidationInputValidCssClassName = 'is-valid'; // change from default of 'input-validation-valid'
v.ValidationMessageCssClassName = 'invalid-feedback'; // change from default of 'field-validation-error'
v.ValidationMessageValidCssClassName = 'valid-feedback'; // change from default of 'field-validation-valid'
//v.ValidationSummaryCssClassName = 'validation-summary-errors'; // unnecessary: bootstrap lacks validation summary component
//v.ValidationSummaryValidCssClassName = 'validation-summary-valid'; // "
v.bootstrap();
var v = new aspnetValidation.ValidationService();
v.highlight = function (input, errorClass, validClass) { ... };
v.unhighlight = function (input, errorClass, validClass) { ... };
v.bootstrap();
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();
FAQs
Enables ASP.NET MVC client-side validation, without jQuery!
The npm package aspnet-client-validation receives a total of 2,048 weekly downloads. As such, aspnet-client-validation popularity was classified as popular.
We found that aspnet-client-validation demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.