NJsonSchema: If I know a field in my schema can only have a few finite values at runtime, can I add this to my validation logic?

1.4k Views Asked by At

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

There are 2 best solutions below

7
Neil On

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; }

    ...
}
0
Rico Suter On

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