ValueValidator

  06. Attributes No Comments

Base class for attributes that can be used to override the default data validation logic for the target.
Implements IValueValidator and ITargetableAttribute interfaces.

Attribute Target

Field, property, indexer, method return value or method parameter.

Example

using System;
using System.Collections.Generic;

using System;
using UnityEngine;

namespace Sisus.Attributes
{
	/// <summary>
	/// Attribute that specifies that its target should only contain number characters.
	/// 
	/// Works on any class members where value implements IEnumerable<char>.
	/// This includes things like string and char[].
	/// 
	/// If value can't be cast to IEnumerable<char> then validation will return false.
	/// </summary>
	[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.ReturnValue | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public class PrimeNumberAttribute : ValueValidatorAttribute
	{
		public PrimeNumberAttribute() : base(Target.Members) { }

		/// <inheritdoc/>
		public override bool Validate(object value)
		{
			#if DEV_MODE
			Debug.Log("Validate: "+value);
			#endif

			int number = (int)value;

			if(number <= 2)
			{
				return number == 2;
			}

			if(number % 2 == 0)
			{
				return false;
			}

			for(int i = 3, stop = (int)Mathf.Floor(Mathf.Sqrt(number)); i <= stop; i += 2)
			{
				if(number % i == 0)
				{
					return false;
				}
			}

			return true;
		}
	}
}
using UnityEngine;
using Sisus.Attributes;

namespace Sisus.Testing
{
	public class PrimeNumberDetector : MonoBehaviour
	{
		[PrimeNumber]
		public int input = 2; //tinted red if not a prime number
	}
}

Example Result