How do I handle data validation

Data validation is a critical aspect of application development. It ensures that the data entered by users meets the specified criteria, enhancing the integrity and quality of the data within your application. Below are common methods to perform data validation in C#.

Data Validation, C#, Input Validation, Data Integrity, Application Development

This content provides an overview of data validation techniques in C#, including using data annotations, custom validation logic, and error handling approaches.

            // Example of Data Validation in C#
            public class User
            {
                [Required(ErrorMessage = "Name is required.")]
                [StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters.")]
                public string Name { get; set; }

                [EmailAddress(ErrorMessage = "Invalid email format.")]
                public string Email { get; set; }

                [Range(18, 100, ErrorMessage = "Age must be between 18 and 100.")]
                public int Age { get; set; }
            }
        
            // Usage in a controller
            public IActionResult Create(User user)
            {
                if (!ModelState.IsValid)
                {
                    // Handle validation errors
                    return View(user);
                }
        
                // Save user data to the database
                return RedirectToAction("Index");
            }
        

Data Validation C# Input Validation Data Integrity Application Development