Int or Number DataType for DataAnnotation validation attribute

前端 未结 8 2437
我寻月下人不归
我寻月下人不归 2020-12-07 10:41

On my MVC3 project, I store score prediction for football/soccer/hockey/... sport game. So one of properties of my prediction class looks like this:

[Range(0         


        
8条回答
  •  执笔经年
    2020-12-07 10:41

    ASP.NET Core 3.1

    This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

    The attribute:

      [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
        public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
        {
            public void AddValidation(ClientModelValidationContext context)
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
                MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
            }
    
            public override bool IsValid(object value)
            {
                return int.TryParse(value?.ToString() ?? "", out int newVal);
            }
    
            private bool MergeAttribute(
                  IDictionary attributes,
                  string key,
                  string value)
            {
                if (attributes.ContainsKey(key))
                {
                    return false;
                }
                attributes.Add(key, value);
                return true;
            }
        }
    

    Client side logic:

    $.validator.addMethod("mustbeinteger",
        function (value, element, parameters) {
            return !isNaN(parseInt(value)) && isFinite(value);
        });
    
    $.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
        options.rules.mustbeinteger = {};
        options.messages["mustbeinteger"] = options.message;
    });
    

    And finally the Usage:

     [MustBeInteger(ErrorMessage = "You must provide a valid number")]
     public int SomeNumber { get; set; }
    

提交回复
热议问题