CodexBloom - Programming Q&A Platform

Unexpected behavior when using custom validation attributes with ASP.NET Core Identity in .NET 7

👀 Views: 19 💬 Answers: 1 📅 Created: 2025-06-06
asp.net-core identity validation C#

I'm trying to implement Quick question that's been bugging me - I'm stuck on something that should probably be simple. I tried several approaches but none seem to work... I'm encountering an unexpected behavior when implementing custom validation attributes for user registration in an ASP.NET Core Identity application using .NET 7. I created a `CustomEmailAttribute` to enforce a specific domain for user emails, but it seems that the validation is not being triggered correctly during the registration process. Here's the custom validation attribute I implemented: ```csharp public class CustomEmailAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var email = value as string; if (string.IsNullOrEmpty(email) || !email.EndsWith("@example.com")) { return new ValidationResult("Email must be from the domain @example.com."); } return ValidationResult.Success; } } ``` Then I used this attribute in my `RegisterViewModel`: ```csharp public class RegisterViewModel { [Required] [EmailAddress] [CustomEmail] public string Email { get; set; } [Required] [DataType(DataType.Password)] [StringLength(100, MinimumLength = 6)] public string Password { get; set; } } ``` In my controller, I'm trying to register the user with: ```csharp public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return RedirectToAction("Index", "Home"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return View(model); } ``` The issue I'm facing is that even when I input an email not matching the specified domain, the `ModelState.IsValid` still returns true, and the validation message is not triggered. I’ve confirmed that the attribute is correctly applied, yet it seems to bypass the validation check. I've tried manually invoking `Validator.TryValidateObject()` before checking `ModelState`, but I still get the same result. Is there something I'm missing in the configuration or registration pipeline? Any insights would be greatly appreciated! For context: I'm using C# on Windows. This is part of a larger API I'm building. How would you solve this?