Class ObjectValidator
Represents an object validator.
Inherited Members
Namespace: Swan.Validators
Syntax
public class ObjectValidator
Examples
The following code describes how to perform a simple object validation.
using Swan.Validators;
class Example
{
public static void Main()
{
// create an instance of ObjectValidator
var obj = new ObjectValidator();
// Add a validation to the 'Simple' class with a custom error message
obj.AddValidator<Simple>(x =>
!string.IsNullOrEmpty(x.Name), "Name must not be empty");
// check if object is valid
var res = obj.IsValid(new Simple { Name = "Name" });
}
class Simple
{
public string Name { get; set; }
}
}
The following code shows of to validate an object with a custom validator and some attributes using the Runtime ObjectValidator singleton.
using Swan.Validators;
class Example
{
public static void Main()
{
// create an instance of ObjectValidator
Runtime.ObjectValidator
.AddValidator<Simple>(x =>
!x.Name.Equals("Name"), "Name must not be 'Name'");
// validate object
var res = Runtime.ObjectValidator
.Validate(new Simple{ Name = "name", Number = 5, Email ="email@mail.com"})
}
class Simple
{
[NotNull]
public string Name { get; set; }
[Range(1, 10)]
public int Number { get; set; }
[Email]
public string Email { get; set; }
}
}
Properties
Current
Gets the current.
Declaration
public static ObjectValidator Current { get; }
Property Value
Type | Description |
---|---|
ObjectValidator | The current. |
Methods
AddValidator<T>(Predicate<T>, String)
Adds a validator to a specific class.
Declaration
public void AddValidator<T>(Predicate<T> predicate, string message)
where T : class
Parameters
Type | Name | Description |
---|---|---|
Predicate<T> | predicate | The predicate that will be evaluated. |
String | message | The message. |
Type Parameters
Name | Description |
---|---|
T | The type of the object. |
IsValid<T>(T)
Validates an object given the specified validators and attributes.
Declaration
public bool IsValid<T>(T target)
Parameters
Type | Name | Description |
---|---|---|
T | target | The object. |
Returns
Type | Description |
---|---|
Boolean |
|
Type Parameters
Name | Description |
---|---|
T | The type. |
Validate<T>(T)
Validates an object given the specified validators and attributes.
Declaration
public ObjectValidationResult Validate<T>(T target)
Parameters
Type | Name | Description |
---|---|---|
T | target | The object. |
Returns
Type | Description |
---|---|
ObjectValidationResult | A validation result. |
Type Parameters
Name | Description |
---|---|
T | The type of the object. |