SoftwareSavant
SoftwareSavant

Reputation: 9767

ajax validation

I am looking to validate a form element using ajax validation using the OnBlur event (to cover key ups and cut and paste events). It looks like jquery Validation 1.9 does indeed have this feature. Can anyone confirm that it covers both key'ed entries in addition to copy/paste entries? Any examples of this using Asp.net MVC2? I do not have a strongly type view so my implementation may end being slightly more complicated that the usual example...

So far, I am going to try and call this function...

public string ValidateHosFin(string hospitalFin)
{
    if (!true)
        return "";
    return "true";

}

This is just a dummy for what the function really will be doing... That is just a test however... So far, I have my jquery Validation function set up like so...

$("#temp1").validate({
        rules: {
            HospitalFinNumber: {
                required: true,
                minlength: 6,
                remote: { url: '<%:Url.Action("ValidateHosFin", "PatientACO")%>', data: { hospitalFin: $('#HospitalFinNumber').val() }
                }
            }
}

The input element id for what I will be validating is HospitalFinNumber. How can I ensure that this will work on both key input event's as well as copy paste events?

Upvotes: 0

Views: 171

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

Yes, this will cover both onBlur events and copy/paste into the field. Also you might want to modify your server side validation action so that it returns an ActionResult and JSON:

public ActionResult ValidateHosFin(string hospitalFin)
{
    // some validation logic
    if (hospitalFin == "1234567") 
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }
    return Json("invalid hospital fin", JsonRequestBehavior.AllowGet);
}

Another remark is your remote validation rule. You should make it return a function or the value sent to the server will be the value that the textbox had at the moment the page was shown (which is probably empty):

$('form').validate({
    rules: {
        HospitalFinNumber: {
            required: true,
            minlength: 6,
            remote: function() {
                return {
                    url: '<%= Url.Action("ValidateHosFin", "PatientACO") %>',
                    data: { hospitalFin: $('#HospitalFinNumber').val() }
                };
            }
        }
    }
});

And here's a live demo.

Upvotes: 1

Related Questions