Skip to main content

Validating Dynamically Loaded Forms

  • 3 minutes to read

This topic describes how to validate the forms that were loaded via callbacks using different validation approaches.

Using unobtrusive client validation approach

The unobtrusive client validation script parses loaded DOM searching for forms with input fields that are decorated with validation attributes. The parsing is only done after the initial page load, so the forms that were loaded via callbacks after the page load, are not parsed.

To enable client-side validation of the newly loaded forms you need to force the parsing of these forms (or a whole document) on the client side. Call the $.validator.unobtrusive.parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.

The code sample below demonstrates how to perform the validation of a dynamically loaded form. In this example, the button click event is handled on the client. The event handler forces the parsing of the required form using the $.validator.unobtrusive.parse() method that enables client-side validation.

View code (Razor):

@Html.BeginForm(){
    ...
    //input fields here
    ...
    @Html.DevExpress().Button(settings => {
            settings.Name = "btnSave";
            settings.Text = "Save";
            settings.UseSubmitBehavior = true;
            settings.ValidationGroup = validationGroup;
            settings.ClientSideEvents.Click = "function(s,e){ PrepareValidationScripts($('#MyEditForm'));}";
        }).GetHtml()
}

Using model validation approach

The model validation script parses loaded DOM searching for forms that contain validation metadata. The parsing is only done after the initial page load, so the forms that were loaded via callbacks after the page load are not parsed. To enable client-side validation of the newly loaded forms, you need to force the parsing of these forms on the client side.

The following example demonstrates how to perform the validation of a dynamically loaded form. In this example, the button click event is handled on the client. The form is submitted to the server only when the IsValid() function returns “True”. The IsValid() function initialize model validation scripts and forces the parsing of the validated form.

View code (Razor):

@Html.BeginForm(){
    ...
    //input fields here
    ...
    @Html.DevExpress().Button(settings => {
            settings.Name = "btnSave";
            settings.Text = "Save";
            settings.UseSubmitBehavior = true;
            settings.ValidationGroup = validationGroup;
            settings.ClientSideEvents.Click = "function(s,e){ e.processOnServer = IsValid(); }";
        }).GetHtml()
}
See Also