Remove required attribute after form built

1 Answer 751 Views
Validation
Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
Lee asked on 14 Sep 2023, 03:08 PM
I have a form on a page with inputs. Some are kendo dropdownlists, some are basic html inputs, etc. That form uses a kendo validator. Normally when I want a field to be required I just add the required attribute to the input or select. That is what I'm doing here. Where the question arises is that as the user is doing other things on the page some of the fields in my form become not required or required again. How do I dynamically change the required state of a field in a kendo form after the form controls and validator have been initialized? Can I simply remove the required attribute from the basic html form element or must I do something more?

1 Answer, 1 is accepted

Sort by
1
Accepted
Zornitsa
Telerik team
answered on 19 Sep 2023, 11:54 AM

Hello Lee,

In order to dynamically change the required state of certain fields in your form, I would suggest removing the "required" attribute from the corresponding element as you had assumed, and also validating the form after that, using the validate() method of the component:

$("#button").click(function () {
      var form = $("#myForm").data("kendoForm");
      form.element.find("input#Name").removeAttr("required");
      form.validate();
});
You could also use the setOptions method of the Form component and change the "required" attribute in the configuration of the items. However, note that this approach would require you to re-initialize not only the item that you want to modify, but all other items from the configuration as well:

$("#button").click(function () {
     form.setOptions({
        items: [{
      		field: "Name",
      		validation: { 
        	     required: false,
      		},
    		}, {
      		field: "Email",
      		validation: { 
        	     required: true,
      		}
    	   }]
      })
});

Below is a small Dojo example, demonstrating the described approaches. The setOptions approach is commented for observing purposes:

Let me know if the proposed suggestions are suitable for your scenario.

Regards,
Zornitsa
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Kendo family, check out our getting started resources
Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
commented on 19 Sep 2023, 12:49 PM

Thanks. Option 1 seems like the simplest.
Tags
Validation
Asked by
Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
Answers by
Zornitsa
Telerik team
Share this question
or