IFieldValidation.cs 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
using Contentful.Core.Configuration;
using Contentful.Core.Search;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;

namespace Contentful.Core.Models.Management
{
    /// <summary>
    /// Represents a validator of a field for a <see cref="ContentType"/>.
    /// </summary>
    [JsonConverter(typeof(ValidationsJsonConverter))]
    public interface IFieldValidator
    {
        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        object CreateValidator();
    }

    /// <summary>
    /// Represents a validator that validates what type of <see cref="ContentType"/> you can link to from a field.
    /// </summary>
    public class LinkContentTypeValidator : IFieldValidator
    {
        /// <summary>
        /// The id of the content types allowed.
        /// </summary>
        public List<string> ContentTypeIds { get; set; }
        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="LinkContentTypeValidator"/>.
        /// </summary>
        /// <param name="message">The custom error message for this validation.</param>
        /// <param name="contentTypeIds">The content types to restrict to.</param>
        public LinkContentTypeValidator(string message = null, params string[] contentTypeIds) : this(contentTypeIds.AsEnumerable(), message)
        {

        }

        /// <summary>
        /// Initializes a new instance of <see cref="LinkContentTypeValidator"/>.
        /// </summary>
        /// <param name="contentTypes">The content types to restrict to.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public LinkContentTypeValidator(IEnumerable<ContentType> contentTypes, string message = null) : this(contentTypes.Select(c => c.SystemProperties.Id), message)
        {

        }

        /// <summary>
        /// Initializes a new instance of <see cref="LinkContentTypeValidator"/>.
        /// </summary>
        /// <param name="contentTypeIds">The content type ids to restrict to.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public LinkContentTypeValidator(IEnumerable<string> contentTypeIds, string message = null)
        {
            ContentTypeIds = new List<string>(contentTypeIds);
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { linkContentType = ContentTypeIds, message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that validates that a field value is in a predefined set of values.
    /// </summary>
    public class InValuesValidator : IFieldValidator
    {
        /// <summary>
        /// The list of values to compare the field value to.
        /// </summary>
        public List<string> RequiredValues { get; set; }

        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="InValuesValidator"/>
        /// </summary>
        /// <param name="message">The custom error message for this validation.</param>
        /// <param name="requiredValues">The values to validate the field value against.</param>
        public InValuesValidator(string message = null, params string[] requiredValues) : this(requiredValues.AsEnumerable(), message)
        {

        }

        /// <summary>
        /// Initializes a new instance of <see cref="InValuesValidator"/>
        /// </summary>
        /// <param name="requiredValues">The values to validate the field value against.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public InValuesValidator(IEnumerable<string> requiredValues, string message = null)
        {
            RequiredValues = new List<string>(requiredValues);
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { @in = RequiredValues, message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that validates that an asset is of a certain <see cref="MimeTypeRestriction"/>
    /// </summary>
    public class MimeTypeValidator : IFieldValidator
    {
        /// <summary>
        /// The mime type groups to validate against.
        /// </summary>
        public List<MimeTypeRestriction> MimeTypes { get; set; }

        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="MimeTypeValidator"/>.
        /// </summary>
        /// <param name="mimeTypes">The mime type groups to validate against.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public MimeTypeValidator(IEnumerable<MimeTypeRestriction> mimeTypes, string message = null)
        {
            MimeTypes = mimeTypes?.ToList();
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { linkMimetypeGroup = MimeTypes.Select(c => c.ToString()?.ToLower()), message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that validates that an array of items conforms to a certain size.
    /// </summary>
    public class SizeValidator : IFieldValidator
    {
        /// <summary>
        /// The minimum number of items in the array.
        /// </summary>
        public int? Min { get; set; }

        /// <summary>
        /// The maximum number of items in the array.
        /// </summary>
        public int? Max { get; set; }

        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="SizeValidator"/>.
        /// </summary>
        /// <param name="min">The minimum number of items in the array.</param>
        /// <param name="max">The maximum number of items in the array.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public SizeValidator(int? min, int? max, string message = null)
        {
            Min = min;
            Max = max;
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { size = new { min = Min, max = Max }, message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that validates that a field value is within a certain range.
    /// </summary>
    public class RangeValidator : IFieldValidator
    {
        /// <summary>
        /// The minimum number for the range.
        /// </summary>
        public int? Min { get; set; }
        /// <summary>
        /// The maximum number for the range.
        /// </summary>
        public int? Max { get; set; }

        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="RangeValidator"/>.
        /// </summary>
        /// <param name="min">The minimum number for the range.</param>
        /// <param name="max">The maximum naumber for the range.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public RangeValidator(int? min, int? max, string message = null)
        {
            Min = min;
            Max = max;
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { range = new { min = Min, max = Max }, message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that validates a field value to conform to a certain regular expression.
    /// </summary>
    public class RegexValidator : IFieldValidator
    {
        /// <summary>
        /// The expression to use.
        /// </summary>
        public string Expression { get; set; }

        /// <summary>
        /// The flags to apply to the regular expression.
        /// </summary>
        public string Flags { get; set; }

        /// <summary>
        /// The custom error message that should be displayed.
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Initializes a new instance of <see cref="RegexValidator"/>.
        /// </summary>
        /// <param name="expression">The regular expression to validate against.</param>
        /// <param name="flags">The flags to apply to the regular expression.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public RegexValidator(string expression, string flags, string message = null)
        {
            Expression = expression;
            Flags = flags;
            Message = message;
        }

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { regexp = new { pattern = Expression, flags = Flags }, message = Message };
        }
    }

    /// <summary>
    /// Represents a validator that ensures that the field value is unique among all entries at the time of publishing.
    /// </summary>
    public class UniqueValidator : IFieldValidator
    {
        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
        public object CreateValidator()
        {
            return new { unique = true };
        }
    }

    /// <summary>
    /// Represents a validator that ensures that the field value is within a certain date range.
    /// </summary>  
    public class DateRangeValidator : IFieldValidator
	{
		private string _min;

		/// <summary>
		/// The minimum allowed date.
		/// </summary>
		public DateTime? Min
		{
			get
			{
                DateTime parsed = new DateTime();
                if (DateTime.TryParse(_min, out parsed))
                    return (DateTime?)parsed;

                return null;
			}
		}

		private string _max;

		/// <summary>
		/// The maximum allowed date.
		/// </summary>
		public DateTime? Max
		{
			get
            {
                DateTime parsed = new DateTime();
                if (DateTime.TryParse(_max, out parsed))
                    return (DateTime?)parsed;

                return null;
			}
		}

		/// <summary>
		/// The custom error message that should be displayed.
		/// </summary>
		public string Message { get; set; }


        /// <summary>
        /// Initializes a new instance of <see cref="DateRangeValidator"/>.
        /// </summary>
        /// <param name="min">The minimum date of the range.</param>
        /// <param name="max">The maximum date of the range.</param>
        /// <param name="message">The custom error message for this validation.</param>
        public DateRangeValidator(string min, string max, string message = null)
		{
			_min = min;
			_max = max;
            Message = message;
		}

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
		public object CreateValidator()
		{
			return new { dateRange = new { min = _min, max = _max }, message = Message };
		}
	}

    /// <summary>
    /// Represents a validator that ensures that the media file size is within a certain size range.
    /// </summary>      
    public class FileSizeValidator : IFieldValidator
	{
		private const int BYTES_IN_KB = 1024;
		private const int BYTES_IN_MB = 1048576;
		/// <summary>
		/// The minimum allowed size of the file.
		/// </summary>
		public int? Min { get; set; }

		/// <summary>
		/// The maximum allowed size of the file.
		/// </summary>
		public int? Max { get; set; }
		/// <summary>
		/// The custom error message that should be displayed.
		/// </summary>
		public string Message { get; set; }

		/// <summary>
		/// Initializes a new instance of <see cref="FileSizeValidator" />.
		/// </summary>
		/// <param name="min">The minimum size of the file.</param>
		/// <param name="max">The maximum size of the file.</param>
		/// <param name="minUnit">The unit measuring the minimum file size.</param>
		/// <param name="maxUnit">The unit measuring the maximum file size.</param>
		/// <param name="message">The custom error message for this validation.</param>
		public FileSizeValidator(int? min, int? max, string minUnit = SystemFileSizeUnits.Bytes, string maxUnit = SystemFileSizeUnits.Bytes, string message = null)
		{
            Min = GetCalculatedByteSize(min, minUnit);
            Max = GetCalculatedByteSize(max, maxUnit);
            Message = message;
		}

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
		public object CreateValidator()
		{
			return new { assetFileSize = new { min = Min, max = Max }, message = Message };
		}


		private int? GetCalculatedByteSize(int? value, string unit)
		{
			if (value != null)
			{
				if (unit == SystemFileSizeUnits.KB)
					value = value * BYTES_IN_KB;
				if (unit == SystemFileSizeUnits.MB)
					value = value * BYTES_IN_MB;
			}
			return value;
		}
	}
    
    /// <summary>
    /// Represents a validator that ensures that the image dimensions are within a certain range.
    /// </summary>   
    public class ImageSizeValidator : IFieldValidator
	{
		/// <summary>
		/// The minimum allowed width of the image (in px).
		/// </summary>
		public int? MinWidth { get; set; }

		/// <summary>
		/// The maximum allowed width of the image (in px).
		/// </summary>
		public int? MaxWidth { get; set; }
		/// <summary>
		/// The minimum allowed height of the iamge (in px).
		/// </summary>
		int? MinHeight { get; set; }

		/// <summary>
		/// The maximum allowed height of the image (in px).
		/// </summary>
		public int? MaxHeight { get; set; }

		/// <summary>
		/// The custom error message that should be displayed.
		/// </summary>
		public string Message { get; set; }


		/// <summary>
		/// Initializes a new instance of <see cref="ImageSizeValidator" />.
		/// </summary>
		/// <param name="minWidth">The minimum width of the image.</param>
		/// <param name="maxWidth">The maximum width of the image.</param>
		/// <param name="minHeight">The minimum height of the image.</param>
		/// <param name="maxHeight">The maximum height of the image.</param>
		/// <param name="message">The custom error message for this validation.</param>
		public ImageSizeValidator(int? minWidth, int? maxWidth, int? minHeight, int? maxHeight, string message = null)
		{
            MinWidth = minWidth;
            MaxWidth = maxWidth;
            MinHeight = minHeight;
            MaxHeight = maxHeight;
            Message = message;
		}

        /// <summary>
        /// Creates a representation of this validator that can be easily serialized.
        /// </summary>
        /// <returns>The object to serialize.</returns>
		public object CreateValidator()
		{
			return new { assetImageDimensions = new { width = new { min = MinWidth, max = MaxWidth }, height = new { min = MinHeight, max = MaxHeight } }, message = Message };
		}
	}
}