The_Outsider
The_Outsider

Reputation: 1925

Validating Data Annotation using Jquery, not displaying the error message

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>

Upvotes: 1

Views: 714

Answers (1)

Rena
Rena

Reputation: 36655

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

Upvotes: 2

Related Questions