1

I need to build a set of customized validation annotations, which some of them assumed to be extension to the already exists annotations and the others assumed to be completely invented.

So please, if that possible, provide me with good resource to learn how to [1] extend or/and [2] invent annotations

Basically, I need help with how to make [Required] annotation optional? I need to extend this to be like [Required(parameter)] so I can somehow pass value to the model to determine the parameter as true or false. So, I can control the annotation if I need it to be applied this time or not.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I don't think the standard `[Required]` annotation will allow anything like this - but you can always write your own, custom data annotation for validation - see e.g. [this other SO question on the topic](https://stackoverflow.com/questions/3413715/how-to-create-custom-data-annotation-validators) as a starting point - or just Google for "C# writing custom data annotation"- you'll get plenty of links to follow – marc_s Jul 19 '20 at 10:21

1 Answers1

0

so I can somehow pass value to the model to determine the parameter as true or false

You can choose to set an custom model validation to finish it, this is this the official link.

And the following is my demo, hope it can help you.

Validation class:

public class RequiredExAttribute : ValidationAttribute
    {
        public string IsFalse { get; set; }
        public string GetErrorMessage() => "Not this name";
        public RequiredExAttribute(string name)
        {
            IsFalse = name;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value.ToString() == IsFalse)
            {
                return new ValidationResult(GetErrorMessage());
            }
            else return ValidationResult.Success;
        }
}

Controller:

public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(JobApplication jobApplication)
        {
                return View();
        }

Model:

public class JobApplication 
    {
        [RequiredEx("Tsai")]
        public string Name { get; set; }      
    }

View:

@model JobApplication
<div asp-validation-summary="ModelOnly" class="text-danger"></div>

<form class="m-1 p-1" method="post">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" type="text" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Submit Application</button>
</form>

<style>
    .input-validation-error {
        border-color: red;
    }
</style>
@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Result:

enter image description here

Jerry Cai
  • 869
  • 1
  • 4
  • 4