diff --git a/_contentTemplates/common/form-validation.md b/_contentTemplates/common/form-validation.md index 9052601295..5367150957 100644 --- a/_contentTemplates/common/form-validation.md +++ b/_contentTemplates/common/form-validation.md @@ -1,3 +1,7 @@ #note-validation >note The Telerik Blazor validation tools provide a way to display different types of validation messages. The main benefit is consistent styling with all other Telerik Blazor components. The validation tools do not expose API or settings for specific validation logic. You should configure the desired standard or custom validation separately, and then use our UI components to display messages to the user. #end + +#note-telerik-role-in-validation +> The Telerik components for Blazor do not perform the actual validation of the model. Validation is managed by the [`EditContext`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.forms.editcontext). The role of the Telerik components is to call `EditContext` methods, subscribe to `EditContext` events, retrieve validation messages, and display them. If a validation scenario does not work as expected, check the behavior in a standard Blazor `` to verify if the issue is related to the Telerik components. +#end diff --git a/components/form/validation.md b/components/form/validation.md index 27293af0d5..ee8fb4803b 100644 --- a/components/form/validation.md +++ b/components/form/validation.md @@ -62,6 +62,8 @@ When you provide an `EditContext` to the form, you can use its [`EnableDataAnnot @[template](/_contentTemplates/common/form-validation.md#note-validation) +@[template](/_contentTemplates/common/form-validation.md#note-telerik-role-in-validation) + ## Validation Message Type With the `ValidationMessageType` parameter of the Telerik Form for Blazor you can customize the way the validation messages are presented to the user. This setting accepts a member of the `FormValidationMessageType` enum: @@ -110,7 +112,7 @@ This section provides the following examples: * [Validate a Complex Model](#validate-a-complex-model) * [Fluent Validation](#fluent-validation) -It is also possible to [trigger Form validation programmatically]({%slug form-overview%}#form-reference-and-methods). +It is also possible to [trigger Form validation programmatically]({%slug form-overview%}#form-reference-and-methods) or [use custom DataAnnotations validation]({%slug validation-kb-custom-dataannotations-validator%}). ### Validate a Model @@ -269,3 +271,8 @@ You can use third-party validation libraries that integrate with the standard `E } } ```` + +## See Also + +* [Custom Form `DataAnnotations` Validation]({%slug validation-kb-custom-dataannotations-validator%}) +* [Conditional Form Validation Options]({%slug form-kb-conditional-validation%}) diff --git a/components/grid/editing/validation.md b/components/grid/editing/validation.md index f9063a1785..c2cbfed8de 100644 --- a/components/grid/editing/validation.md +++ b/components/grid/editing/validation.md @@ -315,6 +315,9 @@ You can validate the Grid with any validator that uses the `EditContext`. To cha } ````` +@[template](/_contentTemplates/common/form-validation.md#note-telerik-role-in-validation) + ## See Also * [Grid Editing]({%slug components/grid/editing/overview%}) +* [Custom Grid `DataAnnotations` Validation]({%slug validation-kb-custom-dataannotations-validator%}) diff --git a/components/validation/overview.md b/components/validation/overview.md index 558639b281..035990e7b9 100644 --- a/components/validation/overview.md +++ b/components/validation/overview.md @@ -118,6 +118,8 @@ You can seamlessly integrate the validation tools with the [Form Component]({%sl } ```` +@[template](/_contentTemplates/common/form-validation.md#note-telerik-role-in-validation) + # Next Steps * Explore [TelerikValidationSummary]({%slug validation-tools-summary%}) diff --git a/knowledge-base/form-conditional-validation.md b/knowledge-base/form-conditional-validation.md index 8d4e6264d7..5abc54f6a6 100644 --- a/knowledge-base/form-conditional-validation.md +++ b/knowledge-base/form-conditional-validation.md @@ -40,7 +40,7 @@ The **TelerikForm** supports any [validator that is compatible with the Blazor E * Perform custom validation in the [Form's `OnSubmit` event]({%slug form-events%}#onsubmit). * Implement [remote (server-side) custom validation](https://github.com/telerik/blazor-ui/tree/master/form/remote-validation). * Use [`FormItem` Templates]({%slug form-formitems-template%}). Subscribe to the **change** handlers of the field editors to execute custom logic, show notifications, etc. -* Implement a [conditional `DataAnnotation` attribute](https://stackoverflow.com/questions/26354853/conditionally-required-property-using-data-annotations). To see inline error messages next to the field editor, use the [`ValidationResult` overload that passes a **field name**](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationresult.-ctor?view=net-6.0#system-componentmodel-dataannotations-validationresult-ctor(system-string-system-collections-generic-ienumerable((system-string)))). In this way the form validator will know which field has failed validation. +* Implement a [custom conditional `DataAnnotations` attribute]({%slug validation-kb-custom-dataannotations-validator%}). To see inline error messages next to the field editor, return the [`ValidationResult` overload that accepts the invalid field name(s)](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationresult). In this way the form validator will know which field has failed validation.
@@ -49,6 +49,10 @@ The **TelerikForm** supports any [validator that is compatible with the Blazor E new List { validationContext.MemberName }); ```` +@[template](/_contentTemplates/common/form-validation.md#note-telerik-role-in-validation) + ## See Also +* [Custom `DataAnnotations` Validation]({%slug validation-kb-custom-dataannotations-validator%}) +* [Fluent Validation]({%slug form-validation%}#fluent-validation) * [Live Demo: DateRangePicker Custom DataAnnotation Attribute](https://demos.telerik.com/blazor-ui/daterangepicker/validation) diff --git a/knowledge-base/validation-custom-dataannotations-validator.md b/knowledge-base/validation-custom-dataannotations-validator.md new file mode 100644 index 0000000000..6cd2bb0e29 --- /dev/null +++ b/knowledge-base/validation-custom-dataannotations-validator.md @@ -0,0 +1,219 @@ +--- +title: Use Custom DataAnnotations Validator +description: Learn how to implement and integrate custom DataAnnotations validation with Telerik Blazor components such as Form, Grid, ValidationMessage, ValidationTooltip, and others. +type: how-to +page_title: How to Use Custom DataAnnotations Validator with Telerik UI for Blazor +slug: validation-kb-custom-dataannotations-validator +tags: telerik, blazor, validation, form, grid +ticketid: 1666005, 1665269, 1658101, 1560189, 1558247, 1543336 +res_type: kb +--- + +## Environment + + + + + + + + +
Product + UI for Blazor,
+ Grid for Blazor,
+ Form for Blazor,
+ ValidationMessage for Blazor,
+ ValidationSummary for Blazor,
+ ValidationTooltip for Blazor +
+ +## Description + +This KB answers the following questions: + +* How to use conditional required validation with Telerik UI for Blazor components? +* How to make a Form field required, depending on the value of another field? +* How to implement a conditional `DataAnnotations` validator and integrate it with the Telerik Blazor Form or Grid? +* How to display inline validation messages or validation tooltips when using a custom validator? + +## Solution + +1. Implement a class that inherits from [`ValidationAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute). +1. Override the [`IsValid()` method overload](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute.isvalid), which accepts a [`ValidationContext`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationcontext) and returns a [`ValidationResult`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationresult). +1. Return a `ValidationResult` that includes the failing field name(s) as a second argument of type `IEnumerable`. This step is crucial in order to apply invalid state to the respective input component and display an inline validation message next to it. +1. (optional) Override the `FormatErrorMessage` method to provide a custom validation message. + +> Creating a custom `DataAnnotations` validator does not involve Telerik APIs and is outside the Telerik support scope. The following implementation is just an example that shows that Telerik Blazor components can work with a custom validator. The exact validator implementation depends on the specific requirements and can vary. + +>caption Use custom conditional required DataAnnotations validator with Telerik components for Blazor + +````CSHTML +@using System.ComponentModel.DataAnnotations + +@using System.Reflection + +

Conditional Validation

+ +

ShippingAddress is required when UseBillingAddressForShipping is false.

+ +

Form

+ + + + + + + + + + + + + +

Grid

+ + + + Add Item + + + + + + + Edit + Save + Cancel + + + + + + +@code { + private OrderDelivery FormModel { get; set; } = new() { Id = 1 }; + + #region Grid + + private List GridData { get; set; } = new(); + + private int LastId { get; set; } + + private void OnGridCreate(GridCommandEventArgs args) + { + var createdItem = (OrderDelivery)args.Item; + + createdItem.Id = ++LastId; + + GridData.Insert(0, createdItem); + } + + private void OnGridUpdate(GridCommandEventArgs args) + { + var updatedItem = (OrderDelivery)args.Item; + var originalItemIndex = GridData.FindIndex(i => i.Id == updatedItem.Id); + + if (originalItemIndex != -1) + { + GridData[originalItemIndex] = updatedItem; + } + } + + #endregion Grid + + #region Model + + public class OrderDelivery + { + public int Id { get; set; } + + [Required] + [Display(Name = "Billing Address")] + public string BillingAddress { get; set; } = string.Empty; + + [Display(Name = "Use Billing Address For Shipping")] + public bool UseBillingAddressForShipping { get; set; } + + [ConditionalRequired(nameof(OrderDelivery.UseBillingAddressForShipping), false)] + [Display(Name = "Shipping Address")] + public string ShippingAddress { get; set; } = string.Empty; + } + + #endregion Model + + #region Custom Validator + + public class ConditionalRequired : ValidationAttribute + { + private string DependentPropertyName { get; set; } + private string DependentPropertyDisplayName { get; set; } = string.Empty; + private object? DependentPropertyExpectedValue { get; set; } + private object? DependentPropertyValue { get; set; } + + public override bool RequiresValidationContext + { + get { return true; } + } + + public ConditionalRequired(string dependentPropertyName, object dependentPropertyExpectedValue) + : base("The {0} field is required when {1} is equal to {2}.") + { + DependentPropertyName = dependentPropertyName; + DependentPropertyExpectedValue = dependentPropertyExpectedValue; + } + + public override string FormatErrorMessage(string requiredPropertyName) + { + return string.Format( + System.Globalization.CultureInfo.CurrentCulture, + base.ErrorMessageString, + requiredPropertyName, + DependentPropertyDisplayName, + DependentPropertyValue); + } + + protected override ValidationResult IsValid(object? validatedValue, ValidationContext validationContext) + { + if (validationContext == null) + { + throw new ArgumentNullException("validationContext"); + } + + PropertyInfo? dependentProperty = validationContext.ObjectType.GetProperty(DependentPropertyName); + DependentPropertyValue = dependentProperty?.GetValue(validationContext.ObjectInstance); + DependentPropertyDisplayName = dependentProperty?.GetCustomAttribute()?.Name ?? DependentPropertyName; + + if ((DependentPropertyValue == null && DependentPropertyExpectedValue == null) + || (DependentPropertyValue != null && DependentPropertyValue.Equals(DependentPropertyExpectedValue)) + && string.IsNullOrEmpty(validatedValue?.ToString())) + { + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new List { validationContext.DisplayName }); + } + + return ValidationResult.Success!; + } + } + + #endregion Custom Validator +} +```` + +@[template](/_contentTemplates/common/form-validation.md#note-telerik-role-in-validation) + +## See Also + +* [Conditional Form Validation Options]({%slug form-kb-conditional-validation%}) +* [Form Validation]({%slug form-validation%}) +* [Grid Validation]({%slug grid-editing-validation%}) +* [Validation Tools Overview]({%slug validation-tools-overview%})