NealR
NealR

Reputation: 10709

Validate a string to be one of two lengths

Is it possible to use ASP MVC's DataAnnotation to require a string to be one of two lengths? This example obviously doesn't work but I am thinking of something along these lines

    [Required]
    [DisplayName("Agent ID")]
    [StringLength(8) || StringLength(10)]
    public string AgentId

Upvotes: 0

Views: 253

Answers (2)

Dan Hunex
Dan Hunex

Reputation: 5318

Yes you can do that . Do a custom validator that inherits from StringLength and this will work for both client and server side

public class CustomStringLengthAttribute : StringLengthAttribute
    {
        private readonly int _firstLength;
        private readonly int _secondLength;


        public CustomStringLengthAttribute(int firstLength, int secondLength)
            : base(firstLength)
        {
            _firstLength = firstLength;
            _secondLength = secondLength;

        }

        public override bool IsValid(object value)
        {

            int valueTobeValidate = value.ToString().Length;

            if (valueTobeValidate == _firstLength)
            {
                return base.IsValid(value);
            }

            if (valueTobeValidate == _secondLength)
            {
                return true;
            }
            return base.IsValid(value);

        }
    }

and register the adapter in the Appplication_start of the Global.asax.cs

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomStringLengthAttribute), typeof(StringLengthAttributeAdapter));

Upvotes: 0

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

You can write your own validation attribute to handle it:

public class UserStringLengthAttribute : ValidationAttribute
    {
        private int _lenght1;
        private int _lenght2;


        public UserStringLengthAttribute(int lenght2, int lenght1)
        {
            _lenght2 = lenght2;
            _lenght1 = lenght1;
        }

        public override bool IsValid(object value)
        {
            var typedvalue = (string) value;
            if (typedvalue.Length != _lenght1 || typedvalue.Length != _lenght2)
            {
                ErrorMessage = string.Format("Length should be {0} or {1}", _lenght1, _lenght2);
                return false;
            }
            return true;
        }
    }

And use it:

[Required]
[DisplayName("Agent ID")]
[UserStringLength(8,10)]
public string AgentId

Upvotes: 3

Related Questions