ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

C# – TimeZoneInfo with current UTC offset

TimeZoneInfo always shows the base UTC offset. This can be confusing because the UTC offset can change based on the date (due to daylight savings rules). Here’s an example showing DateTimeOffset and TimeZoneInfo with different offsets: You can get a date’s UTC offset from DateTimeOffset and combine it with TimeZoneInfo.DisplayName. This approach is implemented in … Read more

C# – How to use TimeZoneInfo

Time zones are complicated and their rules can change, so it makes sense to use a library when you’re dealing with them. One option in .NET is to use the built-in TimeZoneInfo class. Here’s an example of using TimeZoneInfo to get the local system’s time zone: This outputs: Note: The display name always show the … Read more

C# – Get the current date and time

Use DateTime.Now to get the current date/time, like this: This outputs the system’s current date/time: Note: By default, it uses the current culture’s date format (from the OS). This is showing the US date format – MM/dd/yyyy. DateTime.Now is the local date/time from the system where the code is executing. Keep that in mind if … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … Read more