Skip to content

Datavalidering

Backend Dag 6 Agila Projekt, Datavalidering & CORS.pdf
2.3 MB


bild.png

Det räcker att ni har koll på:

Required
Email Adress
Range
StringLength

Validation attributes

Validation attributes let you specify validation rules for model properties. The following example from the shows a model class that is annotated with validation attributes. The [ClassicMovie] attribute is a custom validation attribute and the others are built in. Not shown is [ClassicMovieWithClientValidator], which shows an alternative way to implement a custom attribute.
C#Copy
public class Movie
{
public int Id { get; set; }

[Required]
[StringLength(100)]
public string Title { get; set; } = null!;

[ClassicMovie(1960)]
[DataType(DataType.Date)]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }

[Required]
[StringLength(1000)]
public string Description { get; set; } = null!;

[Range(0, 999.99)]
public decimal Price { get; set; }

public Genre Genre { get; set; }

public bool Preorder { get; set; }
}

Built-in attributes

Here are some of the built-in validation attributes:
: Indicates that a property or parameter should be excluded from validation.
: Validates that the property has a credit card format. Requires.
: Validates that two properties in a model match.
: Validates that the property has an email format.
: Validates that the property has a telephone number format.
: Validates that the property value falls within a specified range.
: Validates that the property value matches a specified regular expression.
: Validates that the field isn't null. Seefor details about this attribute's behavior.
: Validates that a string property value doesn't exceed a specified length limit.
: Validates that the property has a URL format.
: Validates input on the client by calling an action method on the server. Seefor details about this attribute's behavior.
A complete list of validation attributes can be found in the namespace.

Error messages

Validation attributes let you specify the error message to be displayed for invalid input. For example:
C#Copy
[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]

Internally, the attributes call with a placeholder for the field name and sometimes additional placeholders. For example:
C#Copy
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]

When applied to a Name property, the error message created by the preceding code would be "Name length must be between 6 and 8.".
To find out which parameters are passed to String.Format for a particular attribute's error message, see the .

Non-nullable reference types and the [Required] attribute

The validation system treats non-nullable parameters or bound properties as if they had a [Required(AllowEmptyStrings = true)] attribute. By , MVC implicitly starts validating non-nullable properties or parameters as if they had been attributed with the [Required(AllowEmptyStrings = true)] attribute. Consider the following code:
C#Copy
public class Person
{
public string Name { get; set; }
}

If the app was built with <Nullable>enable</Nullable>, a missing value for Name in a JSON or form post results in a validation error. Use a nullable reference type to allow null or missing values to be specified for the Name property:
C#Copy
public class Person
{
public string? Name { get; set; }
}

This behavior can be disabled by configuring in Program.cs:
C#Copy
builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Non-nullable properties on generic types and [Required] attribute

Non-nullable properties on generic types must include the [Required] attribute when the type is required. In the following code, TestRequired is not required:
C#Copy
public class WeatherForecast<T>
{
public string TestRequired { get; set; } = null!;
public T? Inner { get; set; }
}

In the following code, TestRequired is explicitly marked as required:
C#Copy
using System.ComponentModel.DataAnnotations;

public class WeatherForecast<T>
{
[Required] public string TestRequired { get; set; } = null!;
public T? Inner { get; set; }
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.