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.