Skip to content

JADNC: Add required on post validator. #765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/usage/resources/attributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,23 @@ public class Foo : Identifiable
}
}
```

# Custom Validators

Attributes can be marked with custom validators.

## RequiredOnPost Validator Attribute

The 'RequiredOnPost' custom validator attribute can be marked on properties to specify if a value is required on POST requests. This allows the property to be excluded on PATCH requests, making partial patching possible.

The 'RequiredOnPost' custom validator attribute accepts a bool to specify if empty strings are allowed on that property. The default for 'AllowEmptyStrings' is false.

If a PATCH request contains a property assigned the 'RequiredOnPost'custom validator attribute, the requirements of the validator are verified against the patched value, which include that the value is not null and not empty if 'AllowEmptyStrings' is set to false.

```c#
public class Person : Identifiable<int>
{
[RequiredOnPost]
public string FirstName { get; set; }
}
```
2 changes: 2 additions & 0 deletions src/Examples/JsonApiDotNetCoreExample/Models/Article.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using JsonApiDotNetCore.Models;

Expand All @@ -7,6 +8,7 @@ namespace JsonApiDotNetCoreExample.Models
public sealed class Article : Identifiable
{
[Attr]
[RequiredOnPost(true)]
public string Name { get; set; }

[HasOne]
Expand Down
1 change: 1 addition & 0 deletions src/JsonApiDotNetCore/Formatters/JsonApiReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
object model;
try
{
_deserializer.ModelState = context.ModelState;
model = _deserializer.Deserialize(body);
}
catch (InvalidRequestBodyException exception)
Expand Down
1 change: 1 addition & 0 deletions src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<PackageReference Include="Ben.Demystifier" Version="0.1.6" />
<PackageReference Include="Humanizer" Version="2.7.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="$(EFCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.4" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Http;
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;

namespace JsonApiDotNetCore.Models
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class RequiredOnPostAttribute : ValidationAttribute
{
public bool AllowEmptyStrings { get; set; }

/// <summary>
/// Validates that the value is not null or empty on POST operations.
/// </summary>
/// <param name="allowEmptyStrings">Allow empty strings</param>
public RequiredOnPostAttribute(bool allowEmptyStrings = false)
{
AllowEmptyStrings = allowEmptyStrings;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var httpContextAccessor = (IHttpContextAccessor)validationContext.GetRequiredService(typeof(IHttpContextAccessor));
if (httpContextAccessor.HttpContext.Request.Method == "POST")
{
var additionaError = string.Empty;
if (!AllowEmptyStrings)
{
additionaError = " or empty";
}

if (ErrorMessage == null)
{
ErrorMessage = $"The field {validationContext.MemberName} is required and cannot be null{additionaError}.";
}

if (value == null)
{
return new ValidationResult(ErrorMessage);
}

if (!AllowEmptyStrings)
{
if (value is string stringValue && string.IsNullOrEmpty(stringValue))
{
return new ValidationResult(ErrorMessage);
}
}
}
return ValidationResult.Success;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using JsonApiDotNetCore.Models;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace JsonApiDotNetCore.Serialization.Server
{
Expand All @@ -7,6 +8,8 @@ namespace JsonApiDotNetCore.Serialization.Server
/// </summary>
public interface IJsonApiDeserializer
{
public ModelStateDictionary ModelState { get; set; }

/// <summary>
/// Deserializes JSON in to a <see cref="Document"/> and constructs entities
/// from <see cref="ExposableData{T}.Data"/>.
Expand Down
48 changes: 41 additions & 7 deletions src/JsonApiDotNetCore/Serialization/Server/RequestDeserializer.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System;
using JsonApiDotNetCore.Exceptions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Internal.Contracts;
using JsonApiDotNetCore.Models;
using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace JsonApiDotNetCore.Serialization.Server
{
Expand All @@ -13,6 +14,8 @@ public class RequestDeserializer : BaseDocumentParser, IJsonApiDeserializer
{
private readonly ITargetedFields _targetedFields;

public ModelStateDictionary ModelState { get; set; }

public RequestDeserializer(IResourceContextProvider contextProvider, IResourceFactory resourceFactory, ITargetedFields targetedFields)
: base(contextProvider, resourceFactory)
{
Expand All @@ -36,16 +39,47 @@ protected override void AfterProcessField(IIdentifiable entity, IResourceField f
{
if (field is AttrAttribute attr)
{
if (attr.Capabilities.HasFlag(AttrCapabilities.AllowMutate))
if (!attr.Capabilities.HasFlag(AttrCapabilities.AllowMutate))
{
_targetedFields.Attributes.Add(attr);
throw new InvalidRequestBodyException(
"Changing the value of the requested attribute is not allowed.",
$"Changing the value of '{attr.PublicAttributeName}' is not allowed.", null);
}
else


var requiredOnPost = Attribute.GetCustomAttribute(attr.PropertyInfo, typeof(RequiredOnPostAttribute));
if (requiredOnPost != null)
{
throw new InvalidRequestBodyException(
"Changing the value of the requested attribute is not allowed.",
$"Changing the value of '{attr.PublicAttributeName}' is not allowed.", null);
var requiredOnPostAttribute = (RequiredOnPostAttribute)requiredOnPost;
var errorMessage = requiredOnPostAttribute.ErrorMessage;
if (errorMessage == null)
{
errorMessage = $"The field {attr.PropertyInfo.Name} is required and cannot be null.";
}

if (attr.GetValue(entity) == null)
{
if (ModelState != null)
{
ModelState.AddModelError(attr.PropertyInfo.Name, errorMessage);
}
}

if (attr.GetValue(entity) is string stringValue && string.IsNullOrEmpty(stringValue))
{
if (!requiredOnPostAttribute.AllowEmptyStrings)
{
errorMessage = $"The field {attr.PropertyInfo.Name} is required and cannot be null.";
if (ModelState != null)
{
ModelState.AddModelError(attr.PropertyInfo.Name, errorMessage);
}
}
}
}

_targetedFields.Attributes.Add(attr);

}
else if (field is RelationshipAttribute relationship)
_targetedFields.Relationships.Add(relationship);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,10 @@ public async Task Can_Create_Many_To_Many()
data = new
{
type = "articles",
attributes = new Dictionary<string, object>
{
{"name", "An article with relationships"}
},
relationships = new Dictionary<string, dynamic>
{
{ "author", new {
Expand Down
Loading