Dynamic Form Validations

Hi
How do you add dynamic form validations
e.g.) Field Url is only "required" when field checkbox "code" is selected.
You cannot use data annotations as it is is not required when Code is not selected
Thanks

1 Reply 1 reply marked as answer

SN Sevvandhi Nagulan Syncfusion Team October 13, 2020 11:48 AM UTC

Hi Reg,  
 
 
Greetings from Syncfusion support. 
 

We have dynamically created form elements like SfTextbox and SfCheckBox based on the model class members of type string and bool respectively. Also, validated the form. Please find the sample below. 
 


 
 
<EditForm Model="@m_ModelValue"> 
    <DataAnnotationsValidator /> 
    <ValidationSummary /> 
    @foreach (var field in FieldIdentifiers) 
    { 
        @field.Key 
        @CreateComponent(field.Key, field.Value); 
        <br /> 
    } 
    <button type="submit">Submit</button> 
</EditForm> 
 
@code { 
    [Parameter] public User m_ModelValue { get; set; } = new User(); 
    [Parameter] public Dictionary<string, string> FieldIdentifiers { get; set; } = new Dictionary<string, string> { { "FirstName", "string" }, { "Id", "bool" } }; 
    public RenderFragment CreateComponent(string fld, string component) => builder => 
    { 
        if (component == "string") 
        { 
            builder.OpenComponent(0, typeof(SfTextBox)); 
        } 
        if (component == "bool") 
        { 
            builder.OpenComponent(0, typeof(SfCheckBox<bool>)); 
        } 
        builder.CloseComponent(); 
    }; 
 
    public class User 
    { 
        [Required] 
        public string FirstName { get; set; } 
        [Required] 
        public bool? check { get; set; } 
    } 
 
} 

Screenshot:


 
 
    
 

Regards,  
Sevvandhi N 



Marked as answer
Loader.
Up arrow icon