Input Validation in ASP.NET Core and Angular: End-to-End Guide
Input validation in ASP.NET Core done right: server-side allowlists, FluentValidation, length limits, canonicalization and output encoding against XSS.
By Victor Sanchez
Input validation in ASP.NET Core is often treated as "the Angular form already checks it". That assumption showed up again and again in the findings we fix on enterprise web applications. Years earlier, on a legacy desktop app, we had to add special-character validation to dozens of screens after a scan flagged them. Both cases had the same root cause: validation lived in one layer and every other layer trusted it.
Why client-side validation is not security
Client-side validation is UX. It gives fast feedback. It does not protect anything, because anyone can skip the browser and call your API with curl, Postman or a script. Every rule that matters must run on the server, and the client should mirror it, not own it.
// Angular: good UX, zero security
this.form = this.fb.group({
fullName: ['', [Validators.required, Validators.maxLength(100)]],
accountNumber: ['', [Validators.required, Validators.pattern(/^\d{10}$/)]]
});
Allowlists vs blocklists: which should you use?
A blocklist tries to reject known-bad input (<script>, ' OR, --). It always misses something: encodings, Unicode look-alikes, new payloads. An allowlist describes what valid input looks like and rejects everything else. OWASP recommends allowlists for exactly this reason.
| Field | Allowlist rule |
|---|---|
| Account number | Exactly 10 digits |
| Currency code | One of a fixed set (USD, CRC, EUR) |
| Person name | Letters in any language, spaces, apostrophe, hyphen, period; 1 to 100 characters |
| Amount | decimal between 0.01 and a business maximum |
Note the name rule: real names include O'Brien, Núñez and Jean-Luc. A rule of "letters A to Z only" is a bug, not a security control.
How to validate input on the server in ASP.NET Core
DataAnnotations for simple rules
public sealed class TransferRequest
{
[Required, RegularExpression(@"^\d{10}$")]
public string FromAccount { get; init; } = "";
[Required, RegularExpression(@"^\d{10}$")]
public string ToAccount { get; init; } = "";
[Range(typeof(decimal), "0.01", "50000")]
public decimal Amount { get; init; }
[Required, StringLength(3, MinimumLength = 3)]
public string Currency { get; init; } = "";
[Required, StringLength(100, MinimumLength = 1)]
[RegularExpression(@"^[\p{L}\p{M}' .\-]+$")]
public string BeneficiaryName { get; init; } = "";
[StringLength(250)]
public string? Memo { get; init; }
}
With [ApiController], ASP.NET Core returns a 400 with a ValidationProblemDetails body when the model is invalid, before your action runs.
FluentValidation for business rules
When rules depend on each other or on data, FluentValidation is easier to read and test. Its documentation no longer recommends automatic validation through the ASP.NET pipeline, so we call the validator explicitly:
public sealed class TransferRequestValidator : AbstractValidator<TransferRequest>
{
private static readonly string[] Currencies = ["USD", "CRC", "EUR"];
public TransferRequestValidator()
{
RuleFor(x => x.ToAccount).NotEqual(x => x.FromAccount)
.WithMessage("Source and destination must differ.");
RuleFor(x => x.Currency).Must(c => Currencies.Contains(c));
}
}
[HttpPost("transfers")]
public async Task<IActionResult> Create(
TransferRequest request, [FromServices] IValidator<TransferRequest> validator)
{
var result = await validator.ValidateAsync(request);
if (!result.IsValid)
return ValidationProblem(new ValidationProblemDetails(result.ToDictionary()));
// ... the request is valid from here on
}
Protect your regular expressions
A badly written pattern can backtrack for seconds on crafted input (ReDoS). In .NET, set a timeout or use RegexOptions.NonBacktracking (available since .NET 7) for patterns that run on user input:
[GeneratedRegex(@"^[\p{L}\p{M}' .\-]{1,100}$", RegexOptions.None, matchTimeoutMilliseconds: 100)]
private static partial Regex NamePattern();
What is canonicalization and why does it come first?
The same value can be written in many ways: %2e%2e%2f is ../, and Unicode has several forms of é. Validate after you reduce input to its canonical form, or an attacker will send the form your rule does not recognize.
- Decode once. Never decode twice; double decoding is how
%252ebecomes.. - Normalize Unicode with
value.Normalize(NormalizationForm.FormC)before comparing or checking length. - For file paths, resolve with
Path.GetFullPathand check that the result stays under your base directory.
var basePath = Path.GetFullPath(_options.ReportsRoot) + Path.DirectorySeparatorChar;
var fullPath = Path.GetFullPath(Path.Combine(basePath, requestedName));
if (!fullPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
return BadRequest(); // path traversal attempt
Input validation vs output encoding
Validation decides whether data is acceptable. Encoding makes data safe for a specific context. You need both, and one does not replace the other. A valid comment such as Tom & Jerry's "plan" <draft> must be stored as-is and encoded when it is rendered:
- HTML: Razor and Angular interpolation (
{{ value }}) encode by default. Avoid@Html.RawandbypassSecurityTrustHtmlon user content. - SQL: parameters, never encoding. See Stop concatenating SQL.
- Logs: strip CR/LF so users cannot forge log lines.
- CSV exports: prefix values starting with
=,+,-or@to avoid formula injection.
Stripping "dangerous characters" at input time is the classic mistake: it corrupts valid data and still misses contexts you did not think about. Uploaded files are an input too, with their own rules; see secure file-upload endpoints.
Pitfalls
- Relying on Angular validators or
maxlengthattributes as the only check. - Blocklists of "bad" strings instead of allowlists of valid formats.
- Validating before decoding or normalizing.
- Binding request bodies directly to EF entities, which allows mass assignment of fields such as
IsApproved.
Checklist
- Every endpoint validates its input on the server, with dedicated request DTOs.
- Allowlist rules for format, type, range and length on every field.
- Unicode normalization and single decoding before validation.
- Regular expressions with timeouts or
NonBacktracking. - Paths resolved and checked against a base directory.
- Output encoded for its context: HTML, SQL parameters, logs, CSV.
- Client validation mirrors server rules for UX only.
Key takeaways
- Client validation is UX; server validation is security.
- Describe what is valid instead of guessing what is malicious.
- Canonicalize first, then validate.
- Validate on input, encode on output: both, always.
Sources
- OWASP Input Validation Cheat Sheet
- OWASP Cross Site Scripting Prevention Cheat Sheet
- Microsoft Learn: Model validation in ASP.NET Core
- FluentValidation: ASP.NET Core integration
- Microsoft Learn: Best practices for regular expressions in .NET
Need help with input validation in your application?
Santhor reviews and hardens existing Angular and .NET applications, from validation rules and output encoding to the scanner findings they produce, and we build new software with these controls from day one. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. Tell us about your project.