Int or Number DataType for DataAnnotation validation attribute

前端 未结 8 2431
我寻月下人不归
我寻月下人不归 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 11:06

    Use regex in data annotation

    [RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
    public int MaxJsonLength { get; set; }
    
    0 讨论(0)
  • 2020-12-07 11:08

    Try this attribute :

    public class NumericAttribute : ValidationAttribute, IClientValidatable {
    
        public override bool IsValid(object value) {
            return value.ToString().All(c => (c >= '0' && c <= '9') || c == '-' || c == ' ');
        }
    
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "numeric"
            };
            yield return rule;
        }
    }
    

    And also you must register the attribute in the validator plugin:

    if($.validator){
         $.validator.unobtrusive.adapters.add(
            'numeric', [], function (options) {
                options.rules['numeric'] = options.params;
                options.messages['numeric'] = options.message;
            }
        );
    }
    
    0 讨论(0)
提交回复
热议问题