0

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?

Andrew Gray
  • 3,756
  • 3
  • 39
  • 75
  • 1
    It only fires when $.trim returns a value - so for all nonempty and non-whitespace values. – Joe Feb 05 '13 at 20:16

1 Answers1

1

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

Joe
  • 5,389
  • 7
  • 41
  • 63
  • Thank you for the info! Now it's just a matter of informing and reverting. – Andrew Gray Feb 05 '13 at 20:36
  • 1
    Is there a workaround to fires even if $trim is empty? I need to have a field even if it's empty (because the field is only required in some cases) – FredPonch Jul 19 '13 at 08:32