// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.Extensions.Localization; namespace Microsoft.AspNetCore.Mvc.DataAnnotations { /// /// An implementation of which understands data annotation attributes. /// /// The type of the attribute. public abstract class ValidationAttributeAdapter : IClientModelValidator where TAttribute : ValidationAttribute { private readonly IStringLocalizer _stringLocalizer; /// /// Create a new instance of . /// /// The instance to validate. /// The . public ValidationAttributeAdapter(TAttribute attribute, IStringLocalizer stringLocalizer) { Attribute = attribute; _stringLocalizer = stringLocalizer; } /// /// Gets the instance. /// public TAttribute Attribute { get; } /// public abstract void AddValidation(ClientModelValidationContext context); /// /// Adds the given and into /// if does not contain a value for /// . /// /// The HTML attributes dictionary. /// The attribute key. /// The attribute value. /// true if an attribute was added, otherwise false. protected static bool MergeAttribute(IDictionary attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } /// /// Gets the error message formatted using the . /// /// The associated with the model annotated with /// . /// The value arguments which will be used in constructing the error message. /// Formatted error string. protected virtual string GetErrorMessage(ModelMetadata modelMetadata, params object[] arguments) { if (modelMetadata == null) { throw new ArgumentNullException(nameof(modelMetadata)); } if (_stringLocalizer != null && !string.IsNullOrEmpty(Attribute.ErrorMessage) && string.IsNullOrEmpty(Attribute.ErrorMessageResourceName) && Attribute.ErrorMessageResourceType == null) { return _stringLocalizer[Attribute.ErrorMessage, arguments]; } return Attribute.FormatErrorMessage(modelMetadata.GetDisplayName()); } } }