Question

I have received a directive from a superior to use Remote Validation instead of a RequiredIf attribute for checking that a certain field has a value if it is able to be user edited.

Right now, my code looks like this -

View Model

public class FooModel
{
   // SNIP: Unimportant extra variables

   public int? DeviceId;
   public int? ProviderId;

   [Remote("IsMessageRequired", "Foo", 
           AdditionalFields="DeviceId,CarrierId",
           ErrorMessage="(required for other")]
   public string MessageAddress { get;set; }

   // SNIP: Unimportant other details
}

Controller

public class FooController
{
    // SNIP: Unimportant details

    public JsonResult IsMessageRequired(string messageAddress, int? device, int? carrier)
    {
        if(!string.IsNullOrEmpty(messageAddress))
            return Json(true, JsonRequestBehavior.AllowGet);

        // Conditions:
        // A) Device = "Samsung" / Carrier = "Other"
        // B) Device = "Other"

        if(device = FooModel.GetDeviceIdByName("Samsung")
           && carrier = FooModel.GetProviderIdByName("Other")
        {
            return Json(! string.IsNullOrEmpty(pageAddress), JsonRequestBehavior.AllowGet);
        }

        if(device = FooModel.GetDeviceIdByName("Other"))
        {
            return Json(! string.IsNullOrEmpty(pageAddress), JsonRequestBehavior.AllowGet);
        }

        // Default condition occurs on first-run scenarios.
        return Json(true, JsonRequestBehavior.AllowGet);
    }

    // SNIP: Other unimportant details
}

...And finally, my View:

@model FooProject.Models.FooModel

@Html.DropDownFor(x => x.DeviceId)
@Html.DropDownFor(x => x.ProviderId)

@Html.TextBoxFor(x => x.MessageAddress)
@Html.ValidationMessageFor(x => x.MessageAddress)

Question: A validation only fires when a value is entered, but never when the textbox contains no value. Does remote validation only work when there is value in the textbox? If not, how am I approaching this setup incorrectly?

Was it helpful?

Solution

It only fires when $.trim returns a value - so for all nonempty and non-whitespace values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top