November Happy Hour will be moved to Thursday December 5th.
November Happy Hour will be moved to Thursday December 5th.
Hey Andreas,
Whether a form field is required or not is a part of Model.AttributesString, you could parse it and look for "required ".
However, you could maybe do this with js for all required fields, you'd add something like this:
$.each($('*[required="required"]'), function () { var $label = $(this).closest('label.Form__Element__Caption').find('span').addClass('required-asterisk'); var origText = $label.html(); $label.html(origText); });
And have some CSS:
.required-asterisk:after { content: " *"; color: red; }
Hope this helps!
Marija
Hi Andreas,
You can also do this directly without javascript (or if it's turned off it works anyway). If you override the built in episerver form views with your own. Then you can add a row of code in the view to check if the editor have marked the use of the validator "Required" or not. It works for all default validtors, to check if they are active or not for the specific field, even your own if you add any. You need to override the element view anyway to change the markup and so forth.
bool isRequired = formElement.Validators.Any(x => x is EPiServer.Forms.Implementation.Validation.RequiredValidator);
And the complete Razor-view under Views/Shared/ElementBlocks/TextboxElementBlock.cshtml can then look something like this with that bit of code included.
@using System.Web.Mvc @using EPiServer.Forms.Helpers.Internal @using EPiServer.Forms.Implementation.Elements @model TextboxElementBlock @{ var formElement = Model.FormElement; var labelText = Model.Label; bool isRequired = formElement.Validators.Any(x => x is EPiServer.Forms.Implementation.Validation.RequiredValidator); } @{ using (Html.BeginElement(Model, new { @class = "FormTextbox" + Model.GetValidationCssClasses(), data_f_type = "textbox" })) { if(isRequired) { <label style="color: red;">Fältet är obligatoriskt</label> } <label for="@formElement.Guid" class="Form__Element__Caption">@labelText</label> <input name="@formElement.ElementName" id="@formElement.Guid" type="text" class="FormTextbox__Input" placeholder="@Model.PlaceHolder" value="@Model.GetDefaultValue()" @Html.Raw(Model.AttributesString) data-f-datainput /> @(string.Format(Model.GetErrorMessage(), Model.Label)) @Model.RenderDataList() } }
Regards,
Andreas
Is it possible to tell if a form field is required in the view?
To build some kind of usable and accessible forms you want to display if a form field is required before the user submits the form. By adding a "*" or "(required)" text in the form field label and adding the required-attribute to the input element in the HTML code. I cannot seem to figure out how you can access the metadata that tells if the field is required in the view.