0

I am currently working on a basic CRUD web application that uses the Serenity template (Serene) in Visual Studio. This template provides access to multiple plugins. The Sergen plugin generates c# and html files that create a CRUD table for a specified database. The jQuery validate plugin is used to modify clientside field validation. I am trying to add custom field validation to the frequency input field by adding the following combination of jQuery and regex (the commented section) to the TableIndex.cshtml file (generated by Sergen):

{
ViewData["Title"] = Serenity.LocalText.Get("Db.Default.Table.EntityPlural");
}

<div id="GridDiv"></div>


<script type="text/javascript">
jQuery(function () {
    new SerenityNowSolution.Default.TableGrid($('#GridDiv'), {}).init();

    Q.initFullHeightGridPage($('#GridDiv'));
});

//The following is code that I added:

$(document).ready(function () {
    $.validator.addMethod("TableDialog1_Frequency", function (value, element) {
        return this.optional(element) || /(\d)+(d|h|m|s)/.test(value);
    }, "Frequency is invalid: Please enter a valid frequency.");

    $("#TableDialog1_Form").validate({
        rules: {
            TableDialog1_Frequency: "required TableDialog1_Frequency",
        },
    });
});

</script>

As far as I can tell, this is the only cshtml file generated by Sergen. My attempts at adding custom field validation are running into a few issues:

  1. I am unsure about the placement of my added code (if this is the correct file to edit).

  2. My added code currently tries to add validation to the frequency input field by adding a regex rule (method) to the validator function in the validate plugin. Unfortunately, the Sergen generated code "auto-creates" (for lack of a better description) the add-row modal (id = TableDialog#_Form) that contains the frequency input field (id = TableDialog#_Frequency). In my above code, I attempt to add field validation to a specific modal's input field (form/frequency #1). However, every time that the add-row button is clicked on the web page, the appearing modal has a unique identifying number in its ids. It would appear that I need to either edit the modal generation code to remove these numbers, or modify my validate code to account for this. I am unsure of how to do either.

The following code is used to generate the add-row modals (TableDialog#_Form):

namespace SerenityNowSolution.Default {

@Serenity.Decorators.registerClass()
export class TableDialog extends Serenity.EntityDialog<TableRow, any> {
    protected getFormKey() { return TableForm.formKey; }
    protected getIdProperty() { return TableRow.idProperty; }
    protected getLocalTextPrefix() { return TableRow.localTextPrefix; }
    protected getNameProperty() { return TableRow.nameProperty; }
    protected getService() { return TableService.baseUrl; }

    protected form = new TableForm(this.idPrefix);

}
}

Thank you for taking the time to read this. Please let me know if I should show any additional code. Any help would be greatly appreciated.

UPDATE:

This is currently my added code (after making suggested changes):

$(document).ready(function () {
    $.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
    );
});

$(document).on('click', '.tool-button.save-and-close-button', function () {
    var item = $("div.field.Frequency input").attr("id");
    var abc = $("div.s-Form form").attr("id");
    $(abc).validate();
    $(item).rules("add", {
        regex: "^(\d)+(d|h|m|s)$"
    });
    $(abc).validate();
});

$(document).on('click', '.tool-button.apply-changes-button.no-text', function () {
    var item = $("div.field.Frequency input").attr("id");
    var abc = $("div.s-Form form").attr("id");
    $(abc).validate();
    $(item).rules("add", {
        regex: "^(\d)+(d|h|m|s)$"
    });
    $(abc).validate();
});

Unfortunately, field validation is still not occurring.

Jan Molak
  • 4,426
  • 2
  • 36
  • 32
Doe Burner
  • 23
  • 6
  • Are you using the Unobtrusive Validation plugin as part of ASP? If so, then you cannot construct a call to `.validate()` because it will be ignored in favor of the call that is automatically constructed by the Unobtrusive Validation plugin. That is the whole point of using Unobtrusive Validation. – Sparky Jul 19 '18 at 15:37
  • No, I am not using that plugin. I also cannot (or at least don't know how to/can't find it in my solution) access the html code for components of the modal forms, which prevents me from adding data attributes. – Doe Burner Jul 19 '18 at 15:47

1 Answers1

0

Assuming the rest of your approach is correct, you've constructed the rules object incorrectly.

$("#TableDialog1_Form").validate({
    rules: {
        TableDialog1_Frequency: "required TableDialog1_Frequency",
    },
});

You cannot list the rules using this shorthand when there is more than one rule. It's also unclear that you appear to be using the same name on the field and the rule?

Use the key: value pairs for method: parameter like this...

$("#TableDialog1_Form").validate({
    rules: {
        field_name: {  // <- NAME of the field here
            required: true,
            TableDialog1_Frequency: true
        },
        another_field_name: {
            // rules for this field
        }, 
        // remaining fields
    },
    // other validate options, etc.
});

However, every time that the add-row button is clicked on the web page, the appearing modal has a unique identifying number in its ids. It would appear that I need to either edit the modal generation code to remove these numbers, or modify my validate code to account for this. I am unsure of how to do either.

If you have no control or advance knowledge about how the dynamically generated fields is going to be named, then you must use the .rules() method to add the rules programmatically if/when the field is generated.

Examples here and here.

If this is not practical, then you can simply use required and TableDialog1_Frequency as classes on the field and the jQuery Validate plugin will pick those up automatically. This approach works best with rules that have a boolean parameter.

<input name="foo234" type="text" class="required TableDialog1_Frequency" ....

The name will not matter, as long as:

  • the field contains a name
  • name is unique to the form

I also question your choice of naming for the custom method. If the rule is validating input as a time format, then perhaps it should be named something more generic like time. Custom rules can be use on an unlimited number of fields.

Sparky
  • 98,165
  • 25
  • 199
  • 285