C# Sample Programs |
Site Top > C# Sample Programs > C# Sample Programs > ASP.NET Core > Razor Pages
Validate alphanumeric characters (by regular expression)
04/19/2024
This article deals with ASP.NET Core Razor Pages.
All sample programs in this article are based on the Visual Studio Project template "ASP.NET Core Web App" and you must add the Razor pages in th Pages folder.
Validate alphanumeric characters
RegexAlphaNumeric.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace WorkStandard.Pages.validation
{
public class RegexAlphaNumericModel : PageModel
{
[BindProperty]
[DisplayName("Model ID")]
[RegularExpression("[0-9a-zA-Z]*",ErrorMessage = "The {0} must be alphanumeric characters.")]
public string? ModelNumber { get; set; }
public void OnPost()
{
if (!ModelState.IsValid)
{
return;
}
System.Diagnostics.Debug.WriteLine($"No errors.{ModelNumber}");
}
}
}
→ Where Debug.WriteLine outputs to
RegexAlphaNumeric.cshtml
@page
@model WorkStandard.Pages.validation.RegexAlphaNumericModel
<form method="post">
<div class="mb-3">
<label asp-for="ModelNumber"></label>
<input asp-for="ModelNumber" class="form-control" />
<span asp-validation-for="ModelNumber" class="text-danger"></span>
</div>
<div>
<input type="submit" class="btn btn-primary" />
</div>
</form>
@section Scripts {
@{
//Enable client side validation
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
The CSS classes...
- mb-3 Set little margin at bottom.→ Spacing
- form-control Make the input a Bootstrap look.→ Forms
- text-danger The string become red to indicate danger.→ Theme colors
- btn btn-primary Give the button a Bootstrap look to indicate that it's a key feature.→ Buttons