Make field required through javascript

I have fields that are hidden/shown based javascript rules.

I need to make them required if shown but not required if hidden. Can I do that?

Hello @cortese98,

You can make a field required/not required using the code:

//makes a field required
fd.field('FieldName').required = true;

//makes field not required
fd.field('FieldName').required = false;

If the field is hidden I want it false but if it is showing I want it true. How can I do that?

Dear @cortese98,
Make sure that every time you run the command to hide field, you also make it not required and vice versa, like this:

fd.spRendered(function() {
    function hideOrShowDueDate() {
        if (fd.field('StartDate').value) {
            // Show the Due Date field
            $(fd.field('DueDate').$parent.$el).show();
            fd.field('DueDate').required = true;
        } else {
            // Hide the Due Date field
            $(fd.field('DueDate').$parent.$el).hide();
            fd.field('DueDate').required = false;
        }
    }

    // Calling hideOrShowDueDate when the Start Date value changes
    fd.field('StartDate').$on('change',hideOrShowDueDate);

    // Calling hideOrShowDueDate on form loading
    hideOrShowDueDate();
});

This example is based on the one from our documentation, but it's only to show the idea. Each time you hide a field - make it not required, each time you show a field - make it required (if that's necessary).

Please, note that all of these fields must be NOT required in List Settings, otherwise your changes with JavaScript won't help - if the column is required in the List Settings, it won't allow you to submit a form without it.

Dear @Nikita_Kurguzov
I tried to implement your solution, but sadly it does not work completely for me. The required part seams to make some problems.
Any Idea why i get the Error in the consol?


Best regards and thanks for your help
Andreas

Dear @andy,
It says that the fields are undefined - either the field Names are incorrect, or the fields are not yet ready, some fields need to be ready before they can be accessed (Person or Group fields, Lookup fields, etc) - to make sure fields are ready wrap hideOrShowFields() which is called when the form loads like this:

// Calling hideOrShowDueDate on form loading
fd.field('Abtausch-Person').ready(function() {
  fd.field('AbtauschBemerkung').ready(function() {
    fd.field('Abtausch_x002d_Fach').ready(function() {
      hideOrShowDueDate();
    });
  });
});

This is only necessary for some field types, such as Person or Lookup, and not for other field types, such as Single Line, Number or Date.

Also, make sure you've added the fields to the form, or it will not work either.

1 Like