1

I have a model property who's value can be required or not required on the view based on the value of another property. I have implemented it in the view as follows.

<input @Html.Raw(Model.IsRequired ? "required data-val=true' data-val-required='" + Model.Name + " selection is required.'" : "") asp-for="Name" class="form-control" />
if (Model.IsRequired)
{
    <span asp-validation-for="Name" class="text-danger"></span>
}

As indicated based on the Required field value, the validation is applied or not applied.

I also had to add this bit of code.

$("#btnSubmit").on("click", function () {
    $("#form").submit();
});

The code works fine in validation of the code, however the message does not get displayed. What am I missing?

I also tried using this answer and changed my validation span to as below, but it did not work either.

<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
3
  • 1
    You don't need to add these attributes. They are added by the tag helper when you use asp-for. Commented Oct 14, 2019 at 17:04
  • @ChrisPratt I do not add the Required validation on the server side; so does it work even then? Commented Oct 14, 2019 at 17:19
  • @ChrisPratt Removing all the attributes and just the asp-for on the view still does not display the message. Commented Oct 14, 2019 at 19:21

1 Answer 1

2

If you do not want to add Data Annotations for validation.Here is a simple workaound like below:

1.Model:

public class TestModel
{
    public string Name { get; set; }
    public bool IsRequired { get; set; }
}

2.View(You need to change your @Html.Raw() and be sure you have added@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}):

@model TestModel
<form id="form">
    <input @Html.Raw(Model.IsRequired ? "data-val='true' data-val-required='selection is required.'" : "") id="Name" name="Name" type="text" class="input-validation-error" />
    @if (Model.IsRequired)
    {
        <span asp-validation-for="Name" class="text-danger"></span>
    }

    <input id="btnSubmit" type="submit" />
</form>

@section Scripts{
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

3.Controller:

public IActionResult Index()
{
    var test = new TestModel() { IsRequired = true };
    return View(test);
}

4.Result: enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. This works as required. However you might need to remove class="input-validation-error". It seems to load the screen with a red border already instead of doing it on button click.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.