Skip to content

Instantly share code, notes, and snippets.

@Legends
Last active November 10, 2019 07:56
Show Gist options
  • Select an option

  • Save Legends/3923c8fb67352fa0c03086362966d194 to your computer and use it in GitHub Desktop.

Select an option

Save Legends/3923c8fb67352fa0c03086362966d194 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Localization;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator //, IModelValidator
{
string _PropertyNameAttributeIsAppliedTo;
public MustBeTrueAttribute([CallerMemberName]string propertyName = null) // gets the property name
{
_PropertyNameAttributeIsAppliedTo = propertyName;
}
public override bool IsValid(object value)
{
var isvalid = (bool)value;
return isvalid;
}
public void AddValidation(ClientModelValidationContext context)
{
var loc = (IStringLocalizer<SharedResource>)context.ActionContext.HttpContext.RequestServices.GetService(typeof(IStringLocalizer<SharedResource>));
MergeAttribute(context.Attributes, "data-val", "true");
//var errorMessage = FormatErrorMessage(loc[this.ErrorMessage].Value);
var errorMessage = loc[this.ErrorMessage].Value;
MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMessage);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment