📝 Update docs
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
parent
63731015ac
commit
5a2def8b68
@ -1,161 +1,161 @@
|
|||||||
---
|
---
|
||||||
sidebar_position: 5
|
sidebar_position: 5
|
||||||
title: Creation of the add model
|
title: Creation of the add model
|
||||||
---
|
---
|
||||||
|
|
||||||
## Add model
|
## Add model
|
||||||
|
|
||||||
In order to add an element we will create an object representing our item.
|
In order to add an element we will create an object representing our item.
|
||||||
|
|
||||||
For this in create a new class `Models/ItemModel.cs`, this class will include all the information of our API object.
|
For this in create a new class `Models/ItemModel.cs`, this class will include all the information of our API object.
|
||||||
|
|
||||||
We will also add a property so that the user accepts the conditions of addition.
|
We will also add a property so that the user accepts the conditions of addition.
|
||||||
|
|
||||||
Similarly, annotations will be present to validate the fields of our forms.
|
Similarly, annotations will be present to validate the fields of our forms.
|
||||||
|
|
||||||
```csharp title="Models/ItemModel.cs"
|
```csharp title="Models/ItemModel.cs"
|
||||||
public class ItemModel
|
public class ItemModel
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[StringLength(50, ErrorMessage = "The display name must not exceed 50 characters.")]
|
[StringLength(50, ErrorMessage = "The display name must not exceed 50 characters.")]
|
||||||
public string DisplayName { get; set; }
|
public string DisplayName { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[StringLength(50, ErrorMessage = "The name must not exceed 50 characters.")]
|
[StringLength(50, ErrorMessage = "The name must not exceed 50 characters.")]
|
||||||
[RegularExpression(@"^[a-z''-'\s]{1,40}$", ErrorMessage = "Only lowercase characters are accepted.")]
|
[RegularExpression(@"^[a-z''-'\s]{1,50}$", ErrorMessage = "Only lowercase characters are accepted.")]
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[Range(1, 64)]
|
[Range(1, 64)]
|
||||||
public int StackSize { get; set; }
|
public int StackSize { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[Range(1, 125)]
|
[Range(1, 125)]
|
||||||
public int MaxDurability { get; set; }
|
public int MaxDurability { get; set; }
|
||||||
|
|
||||||
public List<string> EnchantCategories { get; set; }
|
public List<string> EnchantCategories { get; set; }
|
||||||
|
|
||||||
public List<string> RepairWith { get; set; }
|
public List<string> RepairWith { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[Range(typeof(bool), "true", "true", ErrorMessage = "You must agree to the terms.")]
|
[Range(typeof(bool), "true", "true", ErrorMessage = "You must agree to the terms.")]
|
||||||
public bool AcceptCondition { get; set; }
|
public bool AcceptCondition { get; set; }
|
||||||
|
|
||||||
[Required(ErrorMessage = "The image of the item is mandatory!")]
|
[Required(ErrorMessage = "The image of the item is mandatory!")]
|
||||||
public byte[] ImageContent { get; set; }
|
public byte[] ImageContent { get; set; }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Concept: Data Annotation
|
## Concept: Data Annotation
|
||||||
|
|
||||||
### Validation attributes
|
### Validation attributes
|
||||||
|
|
||||||
Validation attributes allow you to specify validation rules for model properties.
|
Validation attributes allow you to specify validation rules for model properties.
|
||||||
|
|
||||||
The following example shows a model class that is annotated with validation attributes.
|
The following example shows a model class that is annotated with validation attributes.
|
||||||
The `[ClassicMovie]` attribute is a custom validation attribute, and the others are predefined.
|
The `[ClassicMovie]` attribute is a custom validation attribute, and the others are predefined.
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
public class Movie
|
public class Movie
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[StringLength(100)]
|
[StringLength(100)]
|
||||||
public string Title { get; set; }
|
public string Title { get; set; }
|
||||||
|
|
||||||
[ClassicMovie(1960)]
|
[ClassicMovie(1960)]
|
||||||
[DataType(DataType.Date)]
|
[DataType(DataType.Date)]
|
||||||
[Display(Name = "Release Date")]
|
[Display(Name = "Release Date")]
|
||||||
public DateTime ReleaseDate { get; set; }
|
public DateTime ReleaseDate { get; set; }
|
||||||
|
|
||||||
[Required]
|
[Required]
|
||||||
[StringLength(1000)]
|
[StringLength(1000)]
|
||||||
public string Description { get; set; }
|
public string Description { get; set; }
|
||||||
|
|
||||||
[Range(0, 999.99)]
|
[Range(0, 999.99)]
|
||||||
public decimal Price { get; set; }
|
public decimal Price { get; set; }
|
||||||
|
|
||||||
public Genre Genre { get; set; }
|
public Genre Genre { get; set; }
|
||||||
|
|
||||||
public bool Preorder { get; set; }
|
public bool Preorder { get; set; }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Attributs prédéfinis
|
### Attributs prédéfinis
|
||||||
|
|
||||||
Here are some of the predefined validation attributes:
|
Here are some of the predefined validation attributes:
|
||||||
* `[ValidateNever]`: ValidateNeverAttribute Indicates that a property or parameter should be excluded from validation.
|
* `[ValidateNever]`: ValidateNeverAttribute Indicates that a property or parameter should be excluded from validation.
|
||||||
* `[CreditCard]`: Checks that the property has a credit card format. Requires additional jQuery validation methods.
|
* `[CreditCard]`: Checks that the property has a credit card format. Requires additional jQuery validation methods.
|
||||||
* `[Compare]`: Validates that two properties of a model match.
|
* `[Compare]`: Validates that two properties of a model match.
|
||||||
* `[EmailAddress]`: Checks that the property has an email format.
|
* `[EmailAddress]`: Checks that the property has an email format.
|
||||||
* `[Phone]`: Checks that the property has a phone number format.
|
* `[Phone]`: Checks that the property has a phone number format.
|
||||||
* `[Range]`: Checks that the property value is within a specified range.
|
* `[Range]`: Checks that the property value is within a specified range.
|
||||||
* `[RegularExpression]`: Validates that the property value matches a specified regular expression.
|
* `[RegularExpression]`: Validates that the property value matches a specified regular expression.
|
||||||
* `[Required]`: Checks that the field is not null. For more information on the behavior of this attribute, see [Required] attribute.
|
* `[Required]`: Checks that the field is not null. For more information on the behavior of this attribute, see [Required] attribute.
|
||||||
* `[StringLength]`: Validates that a property value of type String does not exceed a specified length limit.
|
* `[StringLength]`: Validates that a property value of type String does not exceed a specified length limit.
|
||||||
* `[Url]`: Checks that the property has a URL format.
|
* `[Url]`: Checks that the property has a URL format.
|
||||||
* `[Remote]`: Validates input on the client by calling an action method on the server. For more information on the behavior of this attribute, see [Remote] attribute.
|
* `[Remote]`: Validates input on the client by calling an action method on the server. For more information on the behavior of this attribute, see [Remote] attribute.
|
||||||
|
|
||||||
You can find the full list of validation attributes in the [System.ComponentModel.DataAnnotations](https://docs.microsoft.com/fr-fr/dotnet/api/system.componentmodel.dataannotations) namespace.
|
You can find the full list of validation attributes in the [System.ComponentModel.DataAnnotations](https://docs.microsoft.com/fr-fr/dotnet/api/system.componentmodel.dataannotations) namespace.
|
||||||
|
|
||||||
### Error Messages
|
### Error Messages
|
||||||
|
|
||||||
Validation attributes allow you to specify the error message to display for invalid input. For instance :
|
Validation attributes allow you to specify the error message to display for invalid input. For instance :
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
|
[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
|
||||||
```
|
```
|
||||||
|
|
||||||
Internally the attributes call `String.Format` with a placeholder for the field name and sometimes other placeholders. For instance :
|
Internally the attributes call `String.Format` with a placeholder for the field name and sometimes other placeholders. For instance :
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
|
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
|
||||||
```
|
```
|
||||||
|
|
||||||
Applied to a `Name` property, the error message created by the previous code would be "Name length must be between 6 and 8".
|
Applied to a `Name` property, the error message created by the previous code would be "Name length must be between 6 and 8".
|
||||||
|
|
||||||
To find out what parameters are passed to `String.Format` for the error message of a particular attribute, see the [DataAnnotations source code](https://github.com/dotnet/runtime/tree/main/src /libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations).
|
To find out what parameters are passed to `String.Format` for the error message of a particular attribute, see the [DataAnnotations source code](https://github.com/dotnet/runtime/tree/main/src /libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations).
|
||||||
|
|
||||||
### Custom attributes
|
### Custom attributes
|
||||||
|
|
||||||
For scenarios not handled by the predefined validation attributes, you can create custom validation attributes. Create a class that inherits from ValidationAttribute and override the IsValid method.
|
For scenarios not handled by the predefined validation attributes, you can create custom validation attributes. Create a class that inherits from ValidationAttribute and override the IsValid method.
|
||||||
|
|
||||||
The `IsValid` method accepts an object named value, which is the input to validate. An overload also accepts a `ValidationContext` object, which provides additional information such as the model instance created by the model binding.
|
The `IsValid` method accepts an object named value, which is the input to validate. An overload also accepts a `ValidationContext` object, which provides additional information such as the model instance created by the model binding.
|
||||||
|
|
||||||
The following example checks that the release date of a movie belonging to the Classic genre is not later than a specified year. The `[ClassicMovie]` attribute:
|
The following example checks that the release date of a movie belonging to the Classic genre is not later than a specified year. The `[ClassicMovie]` attribute:
|
||||||
* Runs only on the server.
|
* Runs only on the server.
|
||||||
* For classic films, validate the publication date:
|
* For classic films, validate the publication date:
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
public class ClassicMovieAttribute : ValidationAttribute
|
public class ClassicMovieAttribute : ValidationAttribute
|
||||||
{
|
{
|
||||||
public ClassicMovieAttribute(int year)
|
public ClassicMovieAttribute(int year)
|
||||||
{
|
{
|
||||||
Year = year;
|
Year = year;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Year { get; }
|
public int Year { get; }
|
||||||
|
|
||||||
public string GetErrorMessage() =>
|
public string GetErrorMessage() =>
|
||||||
$"Classic movies must have a release year no later than {Year}.";
|
$"Classic movies must have a release year no later than {Year}.";
|
||||||
|
|
||||||
protected override ValidationResult IsValid(object value,
|
protected override ValidationResult IsValid(object value,
|
||||||
ValidationContext validationContext)
|
ValidationContext validationContext)
|
||||||
{
|
{
|
||||||
var movie = (Movie)validationContext.ObjectInstance;
|
var movie = (Movie)validationContext.ObjectInstance;
|
||||||
var releaseYear = ((DateTime)value).Year;
|
var releaseYear = ((DateTime)value).Year;
|
||||||
|
|
||||||
if (movie.Genre == Genre.Classic && releaseYear > Year)
|
if (movie.Genre == Genre.Classic && releaseYear > Year)
|
||||||
{
|
{
|
||||||
return new ValidationResult(GetErrorMessage());
|
return new ValidationResult(GetErrorMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
return ValidationResult.Success;
|
return ValidationResult.Success;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `movie` variable in the previous example represents a `Movie` object that contains the form submission data. When validation fails, a `ValidationResult` with an error message is returned.
|
The `movie` variable in the previous example represents a `Movie` object that contains the form submission data. When validation fails, a `ValidationResult` with an error message is returned.
|
||||||
|
Loading…
Reference in new issue