Postlagerkarte
Postlagerkarte

Reputation: 7117

Defining Custom Client Validation Rules in Asp.net Core MVC

A custom validation attribute in Asp.net core can be implemented by creating a class that implements ValidationAttribute, IClientModelValidator.

In that class one can code the validation rule and emmit the relevant data-val attributes.

On the JavaScript side, we need a function that performs the client side validation.

This can be archived by using .validator.addMethod(...) and $.validator.unobtrusive.adapters.add(...)

This code usually is added to the relevant .js file.

However, I would prefer to emit the javascript code from within my validation attribute. This would make sharing and reusing the attribute much easier.

Any ideas how to achive this?

Upvotes: 0

Views: 937

Answers (1)

Munir Husseini
Munir Husseini

Reputation: 489

There is a new framework called Dryv (from DRY Validation) for exactly this purpose. You can find it under https://dryv-lib.net. You can define your validation rules with lambda expressions in C# and they get translated into JavaScript.

public class Customer
{
    public static readonly DryvRules Rules = DryvRules
        .For<Customer>()
        .Rule(m => m.TaxId,
            m => string.IsNullOrWhiteSpace(m.Company) || !string.IsNullOrWhiteSpace(m.TaxId)
                ? DryvResult.Success
                : $"The tax ID for {m.Company} must be specified.");

    public string Company { get; set; }

    [Required]
    public string Name { get; set; }

    [DryvRules]
    public string TaxId { get; set; }
}

Disclaimer: I am the author of that framework.

Upvotes: 1

Related Questions