Validation of Guid

前端 未结 8 922
忘了有多久
忘了有多久 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:35

    If the custom validation doesn't require a high reuse in your system (i.e. without the need for a custom validation attribute), there's another way to add custom validation to a ViewModel / Posted data model, viz by using IValidatableObject.

    Each error can be bound to one or more model properties, so this approach still works with e.g. Unobtrusive validation in MVC Razor.

    Here's how to check a Guid for default (C# 7.1):

    public class MyModel : IValidatableObject // Implement IValidatableObject
    {
        [Required]
        public string Name {get; set;}
        public Guid SomeGuid {get; set;}
        ... other properties here
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            if (SomeGuid == default)
            {
                yield return new ValidationResult(
                    "SomeGuid must be provided",
                    new[] { nameof(SomeGuid) });
            }
        }
     }
    

    More on IValidatableObject here

提交回复
热议问题