0

Taking an example from their GitHub, if I knew at runtime the First name could ONLY be "Bob" OR "Bill" could I validate against this?

public class Person
{
    [Required]
    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    [Required]
    public string LastName { get; set; }

    public Gender Gender { get; set; }

    [Range(2, 5)]
    public int NumberWithRange { get; set; }

    public DateTime Birthday { get; set; }

    public Company Company { get; set; }

    public Collection<Car> Cars { get; set; }
}

2 Answers2

0

Just create your own attribute:

public class MustBeBobOrBillAttribute : ValidationAttribute 
{
   override bool IsValid(object value) {
        if (value == null) {
            return false;
        }
        var strValue = (string)value;
        return (strValue == "Bob" || strValue == "Bill");
   }
}

Then you can add it to the model:

public class Person
{
    [Required]
    [MustBeBillOrBob]
    public string FirstName { get; set; }

    ...
}
Neil
  • 11,059
  • 3
  • 31
  • 56
  • I don't think NJsonSchema supports the ValidationAttribute: https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaGenerator – Russell Taber Aug 10 '18 at 20:46
  • Are you saying those `[Required]` and `[Range]` attributes don't work either? – Neil Aug 11 '18 at 06:19
  • Required and Range should work, Validation doesnt because it is procedural and there is no way to infer this in the spec via reflection. – Rico Suter Aug 20 '18 at 16:38
  • I don't understand what you mean. All validation attributes are based upon the same base class and are performed via reflection. – Neil Aug 20 '18 at 16:42
  • NJS knows the semantics/meaning of the required and range attributs and has special logic to handle that. However it cannot determine the meaning of your custom attribute because it contains procedural validation logic (in contrast to descriptive) – Rico Suter Aug 20 '18 at 16:47
  • You do realise that range and required are also procedural? Unless they are in a different namespace to the standard ones, all validators that are based on ValidationAttribute, work in the way I've described in my answer. – Neil Aug 20 '18 at 17:02
  • Sure, but it only contains the logic to validate but not to generate a json schema spec for this logic. NJS knows how to handle existing attributes but cannot determine the spec for custom ones (maybe it would be possible a little bit with inspecting the msil, etc but the halting problem would be a problem...) – Rico Suter Aug 20 '18 at 17:45
0

If a string can only be of some given predefined values then it must be described with a JSON Schema enum... here i’d implement this with a custom schema processor (ISchemaProcessor) which adds the enum info and a custom attribute to apply it.

https://github.com/RSuter/NJsonSchema/wiki/Schema-Processors

Rico Suter
  • 11,548
  • 6
  • 67
  • 93