Welcome to our comprehensive guide on ASP .NET and its powerful data validation attributes - Required, StringLength, and Range. Let's dive in and learn these essential tools that will help you build robust and secure applications! 🎯
Before we begin, ensure you have .NET Core SDK installed. Visit Microsoft's official documentation to download and install the SDK.
Now, let's create a new ASP .NET Core Web Application using the CLI:
dotnet new webapi -n MyFirstApp
cd MyFirstApp
In ASP .NET, data validation plays a crucial role in ensuring the integrity of data entering your application. By using data annotations, we can easily validate the data in our models without writing custom validation logic. 📝
The Required attribute ensures that a property must have a value when the model is being validated.
Let's add a simple model and see it in action:
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
public string Name { get; set; }
}In the example above, the Name property is marked as required. Now, let's create a controller and see how the validation works:
using Microsoft.AspNetCore.Mvc;
using MyFirstApp.Models;
namespace MyFirstApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
[HttpPost]
public IActionResult Post([FromBody] Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// ...
}
}
}Now, if you send a POST request with an empty body, you'll receive a 400 Bad Request response, and the error message will be:
{
"Name": ["The Name field is required."]
}The StringLength attribute checks the length of a string against a specified minimum and maximum length.
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[StringLength(50)]
public string Name { get; set; }
}With this attribute, if you send a POST request with a Name that is longer than 50 characters, you'll receive a 400 Bad Request response:
{
"Name": ["The Name must be between 1 and 50 characters."]
}The Range attribute validates a property to be within a specified range of numerical values.
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[Range(18, 100)]
public int Age { get; set; }
}Now, if you send a POST request with an Age outside the range of 18 to 100, you'll receive a 400 Bad Request response:
{
"Age": ["The Age must be greater than or equal to 18 and less than or equal to 100."]
}Combine the attributes to create more complex validation rules:
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[StringLength(50)]
[RegularExpression(@"^[a-zA-Z ]*$")] // Additional validation for a valid name (only alphabets and spaces)
public string Name { get; set; }
[Required]
[Range(18, 100)]
public int Age { get; set; }
}What happens when the `Name` property is empty in the provided model?
With this in-depth lesson, you've now learned about the powerful validation attributes Required, StringLength, and Range in ASP .NET. Start building more secure and robust applications by implementing these essential validation tools in your projects! 💡
Happy coding, and see you in the next tutorial! 🚀