Click here to Skip to main content
15,939,960 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi friends,

Suppose I have a propery of integer type and I am using dataannotation in mvc for validation.

//[MaxLengthSize(10)] Like this I want to create as custom.
Public Int Value {get; set;}

I have a text box when takes greater than 10 values Ex. "11111111111" then It return error

The value '11111111111' is invalid.

Which is the default one. The reason is Int property max value is exceed so, It used default error message.
I have also created a custom validator but not working.

I need to create for showing my validation proper.

I can use jquery validations,working, but I need to do with server side dataannotation only.

kindly help me with solution.
Updated 27-Nov-17 19:41pm

Use Range instead of MaxLength
[Range(1,1000000000,ErrorMessage="Value must be between 1 to 1000000000")]
Share this answer
Faisalabadians 11-Sep-13 10:19am    
+5 for exact answer
I am using this custom data annotation, you can remove minvalue if you like

public sealed class FieldLengthAttribute : ValidationAttribute
        private int _minValue { get; set; }
        private int _maxValue { get; set; }
        public FieldLengthAttribute(int minValue,int maxValue) {

            _minValue = minValue;
            _maxValue = maxValue;

            ErrorMessage = "{0} length should be between {1} and {2}";

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            if (value != null)
                int objectLength = Convert.ToString(value).Length;
                if (objectLength < _minValue || objectLength > _maxValue)
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            return ValidationResult.Success;

        public override string FormatErrorMessage(string name)
            return String.Format(CultureInfo.CurrentCulture,
              ErrorMessageString, name,_minValue,_maxValue);

Share this answer
CHill60 28-Nov-17 4:11am    
The question is over 4 years old and already answered. If you think you have a useful piece of code that someone else might want to use then publish it as a Tip. Don't resurrect old posts - as you see, members will downvote you
Actually the issue is the int has max length is 2147483647 which is 10 digits longer and if I try to pass more than this then return a message and not validate the length.
Return predefine message but not the custom message that we need.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900