ASP.Net mvc 3.0 remote validation

650 Views Asked by At

I have this problem:

I am validating a model in which the sum of 2 attributes can`t be greater than 100. For this i am using as follow:

In my model these are my attributes:

[Remote("ValidatePrevTextWidth", "Validation", AdditionalFields = "TextboxWidth")]
    public int PrevTextWidth { get; set; }

[Remote("ValidateTextboxWidth", "Validation", AdditionalFields = "PrevTextWidth")]
    public int TextboxWidth { get; set; }

My ValidationController has is as follow:

public JsonResult ValidatePrevTextWidth(int PrevTextWidth, int TextboxWidth)
    {
        bool valid = AreValid(PrevTextWidth, TextboxWidth);
        return Json(valido, JsonRequestBehavior.AllowGet);
    }

public JsonResult ValidateTextboxWidth(int TextboxWidth, int PrevTextWidth)
    {            
        bool valid = AreValid(PrevTextWidth, TextboxWidth);
        return Json(valido, JsonRequestBehavior.AllowGet);
    }

private bool AreValid(int prevTextWidth, int textboxWidth)
    {
        return (prevTextWidth + textboxWidth)<=100;
    }

My view is the following:

@using (Html.BeginForm("Index", "Pregunta", FormMethod.Post, new { id = "frmNewPreguntaDesign" }))
{ @Html.TextBoxFor(m => m.PrevTextWidth) 
  @Html.TextBoxFor(m => m.TextboxWidth)
}

That works fine. The problem is the following: Suppose that the prevTextWidth inserted by the user is 55 and he then inserts 46 in the textboxWidth, here the validation fails on the textboxWidth and it appears highlighted.

But what happens if now the user change de value of prevTextWidth to 54? The validation wont fail, but thetextboxWidthwill continue to be highlighted and not valid. The only way to make it valid is to re-insert the value oftextboxWidth`.

So is there a way to validate two attributes at the same time, and not to re-insert the second value to make it valid?

Thanks in advance,

Matias

1

There are 1 best solutions below

2
On

Unfortunately the remote validator only uses the additional field to get the value of that field - it doesn't trigger the validation when that additional field is changed. The JQuery EqualTo (CompareAttribute in MVC) does the same thing.

One way you could achieve what you want is to write a little bit of javascript to validate the first field when the additional field is changed e.g.

 $('#PrevTextWidth').change(function () {
    $('#TextboxWidth').valid();
});