1

In my MVC app I have this View that uses JQuery/AJAX autocomplete, of which this is an extract;

<input type="search" name="searchPrimaryTrade" id="searchPrimaryTrade" 
       data-scd-autocomplete="@Url.Action("AutocompletePrimaryTrade", "DataService")" 
       style = "width: 300px;" data-val="true" class="primaryTrade required" data-val-required="Must enter a Primary Trade"     />
<input type="button" id="ResetPrimaryTrade" value="Reset" class="resetSearch" data-scd-target-searchId="searchPrimaryTrade" style="margin-top:-6px; height:30px;"/><br/>
@Html.HiddenFor(model => model.PrimaryTradeId)
@Html.ValidationMessageFor(model => model.PrimaryTradeId, "*")

When the user selects an item for autcomplete, I use JQuery to populate the hidden field; @Html.HiddenFor(model => model.PrimaryTradeId).

My boss has told me that if the user enters a value in this field, but not selected from autocomplete, then when he clicks out of that field, an error message should display straight away.

How do I implement that?

Jubin Patel
  • 1,959
  • 19
  • 38
arame3333
  • 9,887
  • 26
  • 122
  • 205

1 Answers1

1

You can create a custom validation attribute like this:

public class PrimaryTradeAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value != null && value is int)
        {
            var unitOfWork = new UnitOfWork();
            int primaryTradeId = (int)value;

            // Code to check if the PrimaryTradeId exists in the database...
            if (unitOfWork.PrimaryTradeRepository().Find(primaryTradeId) == null)
            {
                return false;
            }
        }

        return true;
    }
}

Then, you can use this attribute in your Model like this:

[PrimaryTrade]
public int PrimaryTradeId { get; set; }
ataravati
  • 8,891
  • 9
  • 57
  • 89