Validation of Guid

前端 未结 8 928
忘了有多久
忘了有多久 2020-12-31 02:47

I have a strongly-typed view which has a DropDownListFor attribute on it.

Each item in the dropdown list is represented by a GUID.

What I\'m after is a way

8条回答
  •  余生分开走
    2020-12-31 03:43

    I know this is an old question now, but if anyone else is interested I managed to get around this by creating an [IsNotEmpty] annotation (making the Guid nullable wasn't an option in my case).

    This uses reflection to work out whether there's an implementation of Empty on the property, and if so compares it.

    public class IsNotEmptyAttribute : ValidationAttribute
    {
    
        public override bool IsValid(object value)
        {
    
            if (value == null) return false;
    
            var valueType = value.GetType();
            var emptyField = valueType.GetField("Empty");
    
            if (emptyField == null) return true;
    
            var emptyValue = emptyField.GetValue(null);
    
            return !value.Equals(emptyValue);
    
        }
    }
    

提交回复
热议问题