using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace RenoshopBee.Models
{
public class CreditCard
{
[DataType(DataType.CreditCard),
MaxLength(12, ErrorMessage = "Credit card number must be 12 numbers"),
MinLength(12, ErrorMessage = "Credit card number must be 12 numbers")]
public string CNumber { get; set; }
[RegularExpression("^\\d{3}$",ErrorMessage ="CCV must be 3 numbers")]
public int CCV { get; set; }
[DataType(DataType.Date)]
public DateTime ExpireDate { get; set; }
[Key]
public int CustomerId { get; set; }
[ValidateNever]
public Customer customer { get; set; }
}
}
what you see is the code of the CreditCard The use can skip enterening the Credit Card information when SignUp so it will be null credit card
so what to do to skip the validation of null credit card
Well, you might wonder,
ModelState.IsValidconstruct and its executed before hitting the controller so,IsValidalways be false unless you define any property nullable explicitely in your model, threfor, yes of course here in controllerCreditCard?nullable would ignored. As model binding and model validation occur before the execution of a controller action or a Razor Pages handler method. It's the app's responsibility to inspectModelState.IsValidand react appropriately. So you should usecredit cardnullablity inside your model rather in controller because compiler comes first on the model then the controller. Thus, if you would like toCreditCardproperty to be null, therefore, you should set the property null in model not in controller.Model
Note: As you can see I have set
public string? CNumbermeans while submission this propeerty will not be validate. Hence, it will not be considerate on controller as well. If you need more information, you could have a look on our official document here.Output
Let's check above statements in action, Here, be informed that, I haven't set any nullable annotation on property in model and now if I submit with null value it will not hit the controller as you can see below:
Soon after, when I set nullability on
CNumberit's hitting controller even with null value. As can be seen below:Note: Please have a look on this official document.