Skip to content

Instantly share code, notes, and snippets.

@Legends
Created November 9, 2019 15:14
Show Gist options
  • Select an option

  • Save Legends/2b64de51a08a1ae9d9adf3b6bd8c0fbe to your computer and use it in GitHub Desktop.

Select an option

Save Legends/2b64de51a08a1ae9d9adf3b6bd8c0fbe to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Localization;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CurrencyMustMeetCultureAttribute : ValidationAttribute, IClientModelValidator
{
public override bool IsValid(object value)
{
var cc = CultureInfo.CurrentCulture;
//var thSep = cc.NumberFormat.CurrencyGroupSeparator;
var decSep = cc.NumberFormat.CurrencyDecimalSeparator;
var separator = decSep.Equals(".") ? @"\." : decSep; // have it's a dot we have to escape it, otherwise it gets a diff meaning in regex
string pattern = @"^\d{1,}" + separator + @"?\d{0,2}$";
var isMatch = Regex.IsMatch(value.ToString(), pattern);
return isMatch;
}
/// <summary>
/// This exposes the single method AddValidation to create all
/// Html5 data - attributes needed by the client validation rule
/// </summary>
/// <param name="context"></param>
public void AddValidation(ClientModelValidationContext context)
{
var rs = context.ActionContext.HttpContext.RequestServices;
var loc = (IStringLocalizer<SharedResource>)rs.GetService(typeof(IStringLocalizer<SharedResource>));
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = loc[this.ErrorMessage].Value;
MergeAttribute(context.Attributes, "data-val-currencymustmeetculture", 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