JsonFormatStrings

Namespace: NJsonSchema
We found 10 examples in language CSharp for this search. You will see 28 fragments of code.
//-----------------------------------------------------------------------
// <copyright file="PropertyModel.cs" company="NJsonSchema">
//     Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using System.Globalization;
using Threax.NJsonSchema.CodeGeneration.Models;

namespace Threax.NJsonSchema.CodeGeneration.CSharp.Models
{
    /// <summary>The CSharp property template model.</summary>
    public class PropertyModel : PropertyModelBase
    {
        private readonly JsonProperty _property;
        private readonly CSharpGeneratorSettings _settings;
        private readonly CSharpTypeResolver _resolver;

        /// <summary>Initializes a new instance of the <see cref="PropertyModel"/> class.</summary>
        /// <param name="classTemplateModel">The class template model.</param>
        /// <param name="property">The property.</param>
        /// <param name="typeResolver">The type resolver.</param>
        /// <param name="settings">The settings.</param>
        public PropertyModel(
            ClassTemplateModel classTemplateModel,
            JsonProperty property,
            CSharpTypeResolver typeResolver,
            CSharpGeneratorSettings settings)
            : base(property, classTemplateModel, typeResolver, settings)
        {
            _property = property;
            _settings = settings;
            _resolver = typeResolver;
        }

        /// <summary>Gets the name of the property.</summary>
        public string Name => _property.Name;

        /// <summary>Gets the type of the property.</summary>
        public override string Type => _resolver.Resolve(_property.ActualTypeSchema, _property.IsNullable(_settings.SchemaType), GetTypeNameHint());

        /// <summary>Gets a value indicating whether the property has a description.</summary>
        public bool HasDescription => !string.IsNullOrEmpty(_property.Description);

        /// <summary>Gets the description.</summary>
        public string Description => _property.Description;

        /// <summary>Gets the name of the field.</summary>
        public string FieldName => "_" + ConversionUtilities.ConvertToLowerCamelCase(PropertyName, true);

        /// <summary>Gets or sets a value indicating whether empty strings are allowed.</summary>
        public bool AllowEmptyStrings =>
            _settings.SchemaType == SchemaType.JsonSchema &&
            _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) &&
            (_property.MinLength == null || _property.MinLength == 0);

        /// <summary>Gets a value indicating whether this is an array property which cannot be null.</summary>
        public bool HasSetter =>
            (_property.IsNullable(_settings.SchemaType) == false && (
                (_property.ActualTypeSchema.IsArray && _settings.GenerateImmutableArrayProperties) ||
                (_property.ActualTypeSchema.IsDictionary && _settings.GenerateImmutableDictionaryProperties)
            )) == false;

        /// <summary>Gets the json property required.</summary>
        public string JsonPropertyRequiredCode
        {
            get
            {
                if (_settings.RequiredPropertiesMustBeDefined && _property.IsRequired)
                {
                    if (!_property.IsNullable(_settings.SchemaType))
                        return "Newtonsoft.Json.Required.Always";
                    else
                        return "Newtonsoft.Json.Required.AllowNull";
                }
                else
                {
                    if (!_property.IsNullable(_settings.SchemaType))
                        return "Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
                    else
                        return "Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
                }
            }
        }

        /// <summary>Gets a value indicating whether to render a required attribute.</summary>
        public bool RenderRequiredAttribute
        {
            get
            {
                if (!_settings.GenerateDataAnnotations || !_property.IsRequired || _property.IsNullable(_settings.SchemaType))
                    return false;

                return _property.ActualTypeSchema.IsAnyType ||
                       _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Object) ||
                       _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) ||
                       _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Array);
            }
        }

        /// <summary>Gets a value indicating whether to render a range attribute.</summary>
        public bool RenderRangeAttribute
        {
            get
            {
                if (!_settings.GenerateDataAnnotations)
                    return false;

                if (!_property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Number) && !_property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Integer))
                    return false;

                return _property.Maximum.HasValue || _property.Minimum.HasValue;
            }
        }

        /// <summary>Gets the minimum value of the range attribute.</summary>
        public string RangeMinimumValue
        {
            get
            {
                var format =
                    _property.Format == JsonFormatStrings.Double ||
                    _property.Format == JsonFormatStrings.Float ||
                    _property.Format == JsonFormatStrings.Decimal ||
                    _property.Format == JsonFormatStrings.Long ?
                        JsonFormatStrings.Double : JsonFormatStrings.Integer;
                var type =
                    _property.Format == JsonFormatStrings.Double ||
                    _property.Format == JsonFormatStrings.Decimal ?
                        "double" : "int";

                return _property.Minimum.HasValue
                    ? ValueGenerator.GetNumericValue(_property.Type, _property.Minimum.Value, format)
                    : type + "." + nameof(double.MinValue);
            }
        }

        /// <summary>Gets the maximum value of the range attribute.</summary>
        public string RangeMaximumValue
        {
            get
            {
                var format =
                    _property.Format == JsonFormatStrings.Double ||
                    _property.Format == JsonFormatStrings.Float ||
                    _property.Format == JsonFormatStrings.Decimal ||
                    _property.Format == JsonFormatStrings.Long ?
                        JsonFormatStrings.Double : JsonFormatStrings.Integer;
                var type =
                    _property.Format == JsonFormatStrings.Double ||
                    _property.Format == JsonFormatStrings.Decimal ?
                        "double" : "int";

                return _property.Maximum.HasValue
                    ? ValueGenerator.GetNumericValue(_property.Type, _property.Maximum.Value, format)
                    : type + "." + nameof(double.MaxValue);
            }
        }

        /// <summary>Gets a value indicating whether to render a string length attribute.</summary>
        public bool RenderStringLengthAttribute
        {
            get
            {
                if (!_settings.GenerateDataAnnotations)
                    return false;

                if (_property.IsRequired && _property.MinLength == 1 && _property.MaxLength == null)
                    return false; // handled by RequiredAttribute

                return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) &&
                       (_property.MinLength.HasValue || _property.MaxLength.HasValue);
            }
        }

        /// <summary>Gets the minimum value of the string length attribute.</summary>
        public int StringLengthMinimumValue => _property.MinLength ?? 0;

        /// <summary>Gets the maximum value of the string length attribute.</summary>
        public string StringLengthMaximumValue => _property.MaxLength.HasValue ? _property.MaxLength.Value.ToString(CultureInfo.InvariantCulture) : $"int.{nameof(int.MaxValue)}";

        /// <summary>Gets a value indicating whether to render a regular expression attribute.</summary>
        public bool RenderRegularExpressionAttribute
        {
            get
            {
                if (!_settings.GenerateDataAnnotations)
                    return false;

                return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.String) &&
                       !string.IsNullOrEmpty(_property.Pattern);
            }
        }

        /// <summary>Gets the regular expression value for the regular expression attribute.</summary>
        public string RegularExpressionValue => _property.Pattern?.Replace("\"", "\"\"");

        /// <summary>Gets a value indicating whether the property type is string enum.</summary>
        public bool IsStringEnum => _property.ActualTypeSchema.IsEnumeration && _property.ActualTypeSchema.Type == JsonObjectType.String;

        /// <summary>Gets a value indicating whether the property should be formatted like a date.</summary>
        public bool IsDate => _property.Format == JsonFormatStrings.Date;
    }
}


        private static string ResolveNumber(JsonSchema4 schema, bool isNullable)
        {
            if (schema.Format == JsonFormatStrings.Decimal)
                return isNullable ? "decimal?" : "decimal";

            return isNullable ? "double?" : "double";
        }

//-----------------------------------------------------------------------
// <copyright file="JsonFormatStrings.cs" company="NJsonSchema">
//     Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

namespace NJsonSchema
{
    /// <summary>Class containing the constants available as format string. </summary>
    public static class JsonFormatStrings
    {
        /// <summary>Format for a <see cref="DateTime"/>. </summary>
        public const string DateTime = "date-time";

        /// <summary>Format for an email. </summary>
        public const string Email = "email";

        /// <summary>Format for an URI. </summary>
        public const string Uri = "uri";
    }
}

//-----------------------------------------------------------------------
// <copyright file="JsonFormatStrings.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Derived from code (c) Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

namespace Menes.Validation
{
    using System;

    /// <summary>Class containing the constants available as format string. </summary>
    public static class JsonFormatStrings
    {
        /// <summary>Format for a <see cref="System.DateTime"/>. </summary>
        public const string DateTime = "date-time";

        /// <summary>Format for a <see cref="TimeSpan"/>. </summary>
        public const string TimeSpan = "time-span";

        /// <summary>Format for an email. </summary>
        public const string Email = "email";

        /// <summary>Format for an URI. </summary>
        public const string Uri = "uri";

        /// <summary>Format for an GUID. </summary>
        public const string Guid = "guid";

        /// <summary>Format for an UUID (same as GUID). </summary>
        [Obsolete("Now made redundant. Use \"guid\" instead.")]
        public const string Uuid = "uuid";

        /// <summary>Format for an integer. </summary>
        public const string Integer = "int32";

        /// <summary>Format for a long integer. </summary>
        public const string Long = "int64";

        /// <summary>Format for a double number. </summary>
        public const string Double = "double";

        /// <summary>Format for a float number. </summary>
        public const string Float = "float";

        /// <summary>Format for a decimal number. </summary>
        public const string Decimal = "decimal";

        /// <summary>Format for an IP v4 address. </summary>
        public const string IpV4 = "ipv4";

        /// <summary>Format for an IP v6 address. </summary>
        public const string IpV6 = "ipv6";

        /// <summary>Format for binary data encoded with Base64.</summary>
        /// <remarks>Should not be used. Prefer using Byte property of <see cref="JsonFormatStrings"/>.</remarks>
        [Obsolete("Now made redundant. Use \"byte\" instead.")]
        public const string Base64 = "base64";

        /// <summary>Format for a byte if used with numeric type or for base64 encoded value otherwise.</summary>
        public const string Byte = "byte";

        /// <summary>Format for a hostname (DNS name).</summary>
        public const string Hostname = "hostname";

        /// <summary>Format for a phone number.</summary>
        public const string Phone = "phone";

        /// <summary>Format for a full date per RFC3339 Section 5.6.</summary>
        public const string Date = "date";

        /// <summary>Format for a full time per RFC3339 Section 5.6.</summary>
        public const string Time = "time";
    }
}

        /// <summary>Generates the code to convert a data object to the target class instances.</summary>
        /// <returns>The generated code.</returns>
        public static string RenderConvertToJavaScriptCode(DataConversionParameters parameters)
        {
            var model = CreateModel(parameters);
            var template = parameters.Settings.TemplateFactory.CreateTemplate("TypeScript", "ConvertToJavaScript", model);
            return template.Render();
        }

        /// <summary>Generates the code to convert a data object to the target class instances.</summary>
        /// <returns>The generated code.</returns>
        public static string RenderConvertToClassCode(DataConversionParameters parameters)
        {
            var model = CreateModel(parameters);
            var template = parameters.Settings.TemplateFactory.CreateTemplate("TypeScript", "ConvertToClass", model);
            return template.Render();
        }

        private static object CreateModel(DataConversionParameters parameters)
        {
            var type = parameters.Resolver.Resolve(parameters.Schema, parameters.IsPropertyNullable, parameters.TypeNameHint);
            var valueGenerator = parameters.Settings.ValueGenerator;

            var dictionaryValueType = parameters.Resolver.TryResolve(parameters.Schema.AdditionalPropertiesSchema, parameters.TypeNameHint) ?? "any";
            var dictionaryValueDefaultValue = parameters.Schema.AdditionalPropertiesSchema != null
                ? valueGenerator.GetDefaultValue(parameters.Schema.AdditionalPropertiesSchema,
                    parameters.Schema.AdditionalPropertiesSchema.IsNullable(parameters.Settings.SchemaType), dictionaryValueType, parameters.TypeNameHint,
                    parameters.Settings.GenerateDefaultValues, parameters.Resolver)
                : null;

            return new
            {
                NullValue = parameters.NullValue.ToString().ToLowerInvariant(),

                Variable = parameters.Variable,
                Value = parameters.Value,

                HasDefaultValue = valueGenerator.GetDefaultValue(parameters.Schema, 
                    parameters.IsPropertyNullable, type, parameters.TypeNameHint, parameters.Settings.GenerateDefaultValues, parameters.Resolver) != null,
                DefaultValue = valueGenerator.GetDefaultValue(parameters.Schema, 
                    parameters.IsPropertyNullable, type, parameters.TypeNameHint, parameters.Settings.GenerateDefaultValues, parameters.Resolver),

                Type = type,

                IsNewableObject = IsNewableObject(parameters.Schema),
                IsDate = IsDate(parameters.Schema.Format, parameters.Settings.DateTimeType),
                IsDateTime = IsDateTime(parameters.Schema.Format, parameters.Settings.DateTimeType),

                IsDictionary = parameters.Schema.IsDictionary,
                DictionaryValueType = dictionaryValueType,
                DictionaryValueDefaultValue = dictionaryValueDefaultValue,
                HasDictionaryValueDefaultValue = dictionaryValueDefaultValue != null,

                IsDictionaryValueNewableObject = parameters.Schema.AdditionalPropertiesSchema != null && IsNewableObject(parameters.Schema.AdditionalPropertiesSchema),
                IsDictionaryValueDate = IsDate(parameters.Schema.AdditionalPropertiesSchema?.ActualSchema?.Format, parameters.Settings.DateTimeType),
                IsDictionaryValueDateTime = IsDateTime(parameters.Schema.AdditionalPropertiesSchema?.ActualSchema?.Format, parameters.Settings.DateTimeType),
                IsDictionaryValueNewableArray = parameters.Schema.AdditionalPropertiesSchema?.ActualSchema?.IsArray == true &&
                    IsNewableObject(parameters.Schema.AdditionalPropertiesSchema.Item),
                DictionaryValueArrayItemType = parameters.Schema.AdditionalPropertiesSchema?.ActualSchema?.IsArray == true ?
                    parameters.Resolver.TryResolve(parameters.Schema.AdditionalPropertiesSchema.Item, "Anonymous") ?? "any" : "any",

                IsArray = parameters.Schema.IsArray,
                ArrayItemType = parameters.Resolver.TryResolve(parameters.Schema.Item, parameters.TypeNameHint) ?? "any",
                IsArrayItemNewableObject = parameters.Schema.Item != null && IsNewableObject(parameters.Schema.Item),
                IsArrayItemDate = IsDate(parameters.Schema.Item?.Format, parameters.Settings.DateTimeType),
                IsArrayItemDateTime = IsDateTime(parameters.Schema.Item?.Format, parameters.Settings.DateTimeType),

                //StringToDateCode is used for date and date-time formats
                UseJsDate = parameters.Settings.DateTimeType == TypeScriptDateTimeType.Date,
                StringToDateCode = parameters.Settings.DateTimeType == TypeScriptDateTimeType.Date ? 
                    "new Date" : 
                    (parameters.Settings.DateTimeType == TypeScriptDateTimeType.OffsetMomentJS ? "moment.parseZone" : "moment"),
                DateTimeToStringCode = parameters.Settings.DateTimeType == TypeScriptDateTimeType.OffsetMomentJS ? "toISOString(true)" : "toISOString()",

                HandleReferences = parameters.Settings.HandleReferences
            };
        }

        private static bool IsDateTime(string format, TypeScriptDateTimeType type)
        {
            // TODO: Make this more generic (see TypeScriptTypeResolver.ResolveString)
            if (type == TypeScriptDateTimeType.Date)
            {
                if (format == JsonFormatStrings.DateTime)
                    return true;

                if (format == JsonFormatStrings.Time)
                    return false;

                if (format == JsonFormatStrings.TimeSpan)
                    return false;
            }
            else if (type == TypeScriptDateTimeType.MomentJS || 
                     type == TypeScriptDateTimeType.OffsetMomentJS)
            {
                if (format == JsonFormatStrings.DateTime)
                    return true;

                if (format == JsonFormatStrings.Time)
                    return true;

                if (format == JsonFormatStrings.TimeSpan)
                    return true;
            }
            return false;
        }


        private static bool IsDate(string format, TypeScriptDateTimeType type)
        {
            // TODO: Make this more generic (see TypeScriptTypeResolver.ResolveString)
            if (type == TypeScriptDateTimeType.Date)
            {
                if (format == JsonFormatStrings.Date)
                    return true;
            }
            else if (type == TypeScriptDateTimeType.MomentJS || 
                     type == TypeScriptDateTimeType.OffsetMomentJS)
            {
                if (format == JsonFormatStrings.Date)
                    return true;
            }
            return false;
        }

        private static bool IsNewableObject(JsonSchema4 schema)
        {
            schema = schema.ActualSchema;
            return (schema.Type.HasFlag(JsonObjectType.Object) || schema.Type == JsonObjectType.None) 
                && !schema.IsAnyType && !schema.IsDictionary && !schema.IsEnumeration;
        }

//-----------------------------------------------------------------------
// <copyright file="JsonFormatStrings.cs" company="NJsonSchema">
//     Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using System;

namespace NJsonSchema
{
    /// <summary>Class containing the constants available as format string. </summary>
    public static class JsonFormatStrings
    {
        /// <summary>Format for a <see cref="System.DateTime"/>. </summary>
        public const string DateTime = "date-time";

        /// <summary>Format for a <see cref="TimeSpan"/>. </summary>
        public const string TimeSpan = "time-span";

        /// <summary>Format for an email. </summary>
        public const string Email = "email";

        /// <summary>Format for an URI. </summary>
        public const string Uri = "uri";

        /// <summary>Format for an GUID. </summary>
        public const string Guid = "guid";

        /// <summary>Format for an IP v4 address. </summary>
        public const string IpV4 = "ipv4";

        /// <summary>Format for binary data encoded with Base64.</summary>
        public const string Base64 = "base64";

        /// <summary>Format for a byte.</summary>
        public const string Byte = "byte";

        /// <summary>Format for a hostname (DNS name).</summary>
        public const string Hostname = "hostname";
    }
}

        public static void AddSquidexOpenApiSettings(this IServiceCollection services)
        {
            services.AddSingletonAs<ErrorDtoProcessor>()
                .As<IDocumentProcessor>();

            services.AddSingletonAs<RuleActionProcessor>()
                .As<IDocumentProcessor>();

            services.AddSingletonAs<CommonProcessor>()
                .As<IDocumentProcessor>();

            services.AddSingletonAs<XmlTagProcessor>()
                .As<IDocumentProcessor>();

            services.AddSingletonAs<SecurityProcessor>()
                .As<IDocumentProcessor>();

            services.AddSingletonAs<ScopesProcessor>()
                .As<IOperationProcessor>();

            services.AddSingletonAs<FixProcessor>()
                .As<IOperationProcessor>();

            services.AddSingletonAs<TagByGroupNameProcessor>()
                .As<IOperationProcessor>();

            services.AddSingletonAs<XmlResponseTypesProcessor>()
                .As<IOperationProcessor>();

            services.AddSingletonAs<JsonSchemaGenerator>()
                .AsSelf();

            services.AddSingletonAs<OpenApiSchemaGenerator>()
                .AsSelf();

            services.AddSingleton(c =>
            {
                var settings = new JsonSchemaGeneratorSettings
                {
                    SerializerSettings = c.GetRequiredService<JsonSerializerSettings>()
                };

                ConfigureSchemaSettings(settings, true);

                return settings;
            });

            services.AddSingleton(c =>
            {
                var settings = new OpenApiDocumentGeneratorSettings
                {
                    SerializerSettings = c.GetRequiredService<JsonSerializerSettings>()
                };

                ConfigureSchemaSettings(settings, true);

                foreach (var processor in c.GetRequiredService<IEnumerable<IDocumentProcessor>>())
                {
                    settings.DocumentProcessors.Add(processor);
                }

                return settings;
            });

            services.AddOpenApiDocument(settings =>
            {
                settings.Title = "Squidex API";

                ConfigureSchemaSettings(settings);

                settings.OperationProcessors.Add(new QueryParamsProcessor("/apps/{app}/assets"));
            });
        }

        private static void ConfigureSchemaSettings(JsonSchemaGeneratorSettings settings, bool flatten = false)
        {
            settings.AllowReferencesWithProperties = true;

            settings.TypeMappers = new List<ITypeMapper>
            {
                CreateStringMap<DomainId>(),
                CreateStringMap<Instant>(JsonFormatStrings.DateTime),
                CreateStringMap<LocalDate>(JsonFormatStrings.Date),
                CreateStringMap<LocalDateTime>(JsonFormatStrings.DateTime),
                CreateStringMap<Language>(),
                CreateStringMap<NamedId<DomainId>>(),
                CreateStringMap<NamedId<Guid>>(),
                CreateStringMap<NamedId<string>>(),
                CreateStringMap<RefToken>(),
                CreateStringMap<Status>(),

                CreateObjectMap<JsonObject>(),
                CreateObjectMap<AssetMetadata>()
            };

            settings.FlattenInheritanceHierarchy = flatten;
        }

        private static ITypeMapper CreateObjectMap<T>()
        {
            return new PrimitiveTypeMapper(typeof(T), schema =>
            {
                schema.Type = JsonObjectType.Object;

                schema.AdditionalPropertiesSchema = new JsonSchema
                {
                    Description = "Any"
                };
            });
        }

        private static ITypeMapper CreateStringMap<T>(string? format = null)
        {
            return new PrimitiveTypeMapper(typeof(T), schema =>
            {
                schema.Type = JsonObjectType.String;

                schema.Format = format;
            });
        }

        public static JsonSchema Object()
        {
            return new JsonSchema { Type = JsonObjectType.Object };
        }

        public static JsonSchema Guid()
        {
            return new JsonSchema { Type = JsonObjectType.String, Format = JsonFormatStrings.Guid };
        }

        public static JsonSchema String()
        {
            return new JsonSchema { Type = JsonObjectType.String };
        }

        public static JsonSchemaProperty ArrayProperty(JsonSchema item, string? description = null, bool isRequired = false)
        {
            return Enrich(new JsonSchemaProperty { Type = JsonObjectType.Array, Item = item }, description, isRequired);
        }

        public static JsonSchemaProperty BooleanProperty(string? description = null, bool isRequired = false)
        {
            return Enrich(new JsonSchemaProperty { Type = JsonObjectType.Boolean }, description, isRequired);
        }

        public static JsonSchemaProperty DateTimeProperty(string? description = null, bool isRequired = false)
        {
            return Enrich(new JsonSchemaProperty { Type = JsonObjectType.String, Format = JsonFormatStrings.DateTime }, description, isRequired);
        }


        /// <summary>Validates the given data, throwing an <see cref="OpenApiBadRequestException"/> augmented with <see cref="OpenApiProblemDetailsExtensions"/> detailing the errors.</summary>
        /// <param name="data">The data.</param>
        /// <param name="schema">The schema.</param>
        public void ValidateAndThrow(string data, OpenApiSchema schema)
        {
            if (this.logger.IsEnabled(LogLevel.Debug))
            {
                this.logger.LogDebug("Attempting to validate data to [{schema}]", schema.GetLoggingInformation());
            }

            ICollection<ValidationError> errors = this.Validate(data, schema);

            if (errors.Count > 0)
            {
                Exception exception = new OpenApiBadRequestException("Schema Validation Error", "The content does not conform to the required schema.")
                    .AddProblemDetailsExtension("validationErrors", errors);

                this.logger.LogError(
                    "Failed to validate data to [{schema}], The content does not conform to the required schema, [{errors}]",
                    schema.GetLoggingInformation(),
                    errors.Select(error => new { error.Kind, error.Property, error.LineNumber, error.LinePosition }));
                throw exception;
            }
        }

        /// <summary>Validates the given data, throwing an <see cref="OpenApiBadRequestException"/> augmented with <see cref="OpenApiProblemDetailsExtensions"/> detailing the errors.</summary>
        /// <param name="data">The data.</param>
        /// <param name="schema">The schema.</param>
        public void ValidateAndThrow(JToken? data, OpenApiSchema schema)
        {
            if (this.logger.IsEnabled(LogLevel.Debug))
            {
                this.logger.LogDebug("Attempting to validate data to [{schema}]", schema.GetLoggingInformation());
            }

            data ??= JValue.CreateNull();

            ICollection<ValidationError> errors = this.Validate(data, schema);

            if (errors.Count > 0)
            {
                Exception exception = new OpenApiBadRequestException("Schema Validation Error", "The content does not conform to the required schema.")
                    .AddProblemDetailsExtension("validationErrors", errors);

                throw exception;
            }
        }

        /// <summary>Validates the given data.</summary>
        /// <param name="data">The data.</param>
        /// <param name="schema">The schema.</param>
        /// <returns>The list of validation errors.</returns>
        private ICollection<ValidationError> Validate(string data, OpenApiSchema schema)
        {
            bool dataShouldBeJson = schema.Type == "object" || schema.Type == "array" || schema.Type == null;
            JToken jsonObject = dataShouldBeJson ? JToken.Parse(data) : data;

            return this.Validate(jsonObject, schema);
        }

        /// <summary>Validates the given JSON token.</summary>
        /// <param name="token">The token.</param>
        /// <param name="schema">The schema.</param>
        /// <returns>The list of validation errors.</returns>
        private ICollection<ValidationError> Validate(JToken token, OpenApiSchema schema)
        {
            return this.Validate(token, schema, null, token.Path);
        }

        /// <summary>Validates the given JSON token.</summary>
        /// <param name="token">The token.</param>
        /// <param name="schema">The schema.</param>
        /// <param name="propertyName">The current property name.</param>
        /// <param name="propertyPath">The current property path.</param>
        /// <returns>The list of validation errors.</returns>
        private ICollection<ValidationError> Validate(JToken token, OpenApiSchema schema, string? propertyName, string propertyPath)
        {
            var errors = new List<ValidationError>();

            this.ValidateAnyOf(token, schema, propertyName, propertyPath, errors);
            this.ValidateAllOf(token, schema, propertyName, propertyPath, errors);
            this.ValidateOneOf(token, schema, propertyName, propertyPath, errors);
            this.ValidateNot(token, schema, propertyName, propertyPath, errors);
            this.ValidateType(token, schema, propertyName, propertyPath, errors);
            this.ValidateEnum(token, schema, propertyName, propertyPath, errors);
            this.ValidateProperties(token, schema, propertyName, propertyPath, errors);

            return errors;
        }

        private void ValidateType(JToken token, OpenApiSchema schema, string? propertyName, string propertyPath, List<ValidationError> errors)
        {
            var types = this.GetTypes(schema).ToDictionary(t => t, _ => (ICollection<ValidationError>)new List<ValidationError>());

            if (types.Count > 1)
            {
                foreach (KeyValuePair<JsonObjectType, ICollection<ValidationError>> type in types)
                {
                    this.ValidateArray(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateString(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateNumber(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateInteger(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateBoolean(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateNull(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                    this.ValidateObject(token, schema, type.Key, propertyName, propertyPath, (List<ValidationError>)type.Value);
                }

                // just one has to validate when multiple types are defined
                if (types.All(t => t.Value.Count > 0))
                {
                    errors.Add(new MultiTypeValidationError(ValidationErrorKind.NoTypeValidates, propertyName, propertyPath, types, token, schema));
                }
            }
            else
            {
                var jsonObjectType = this.ToJsonObjectType(schema.Type);

                this.ValidateArray(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateString(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateNumber(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateInteger(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateBoolean(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateNull(token, schema, jsonObjectType, propertyName, propertyPath, errors);
                this.ValidateObject(token, schema, jsonObjectType, propertyName, propertyPath, errors);
            }
        }

//-----------------------------------------------------------------------
// <copyright file="JsonFormatStrings.cs" company="NJsonSchema">
//     Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using System;

namespace Threax.NJsonSchema
{
    /// <summary>Class containing the constants available as format string. </summary>
    public static class JsonFormatStrings
    {
        /// <summary>Format for a <see cref="System.DateTime"/>. </summary>
        public const string DateTime = "date-time";

        /// <summary>Format for a <see cref="TimeSpan"/>. </summary>
        public const string TimeSpan = "time-span";

        /// <summary>Format for an email. </summary>
        public const string Email = "email";

        /// <summary>Format for an URI. </summary>
        public const string Uri = "uri";

        /// <summary>Format for an GUID. </summary>
        public const string Guid = "guid";

        /// <summary>Format for an UUID (same as GUID). </summary>
        [Obsolete("Now made redundant. Use \"guid\" instead.")]
        public const string Uuid = "uuid";

        /// <summary>Format for an integer. </summary>
        public const string Integer = "int32";

        /// <summary>Format for a long integer. </summary>
        public const string Long = "int64";

        /// <summary>Format for a double number. </summary>
        public const string Double = "double";

        /// <summary>Format for a float number. </summary>
        public const string Float = "float";

        /// <summary>Format for a decimal number. </summary>
        public const string Decimal = "decimal";

        /// <summary>Format for an IP v4 address. </summary>
        public const string IpV4 = "ipv4";

        /// <summary>Format for an IP v6 address. </summary>
        public const string IpV6 = "ipv6";

        /// <summary>Format for binary data encoded with Base64.</summary>
        /// <remarks>Should not be used. Prefer using Byte property of <see cref="JsonFormatStrings"/></remarks>
        [Obsolete("Now made redundant. Use \"byte\" instead.")]
        public const string Base64 = "base64";

        /// <summary>Format for a byte if used with numeric type or for base64 encoded value otherwise.</summary>
        public const string Byte = "byte";

        /// <summary>Format for a hostname (DNS name).</summary>
        public const string Hostname = "hostname";

        /// <summary>Format for a phone number.</summary>
        public const string Phone = "phone";

        /// <summary>Format for a full date per RFC3339 Section 5.6.</summary>
        public const string Date = "date";

        /// <summary>Format for a full time per RFC3339 Section 5.6.</summary>
        public const string Time = "time";
    }
}

NJsonSchema.JsonFormatStrings : Object

Fields :

public static String DateTime
public static String TimeSpan
public static String Email
public static String Uri
public static String Guid
public static String Uuid
public static String Integer
public static String Long
public static String Double
public static String Float
public static String Decimal
public static String IpV4
public static String IpV6
public static String Base64
public static String Byte
public static String Binary
public static String Hostname
public static String Phone
public static String Date
public static String Time

Methods :

public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()