logo

Form

High performance Form component with data scope management. Including data collection, verification, and styles.

When to use

  • When you need to create an instance or collect information.
  • When you need to validate fields in certain rules.

Examples

Basic Form data control. Includes layout, initial values, validation and submit.

expand code expand code

Get form ref with @ref.

expand code expand code

Form supports .NET 8's static server-side rendered form validation with the following limitations:

  1. The Name parameter of Form component must be set. Method and Enhance can also be set. (corresponding to the EditForm's FormName, Method, and Enhance)
  2. The property binding of the Form component must use Model.Field, not @context.Field.
  3. The bound Model instance needs to be marked with the [SupplyParameterFromForm] feature. If there are multiple forms, the FormName parameter must be consistent with the Name of the Form.

Notice:

  1. Due to the loss of interactivity in static pages, the supported components are limited to Input, InputPassword, TextArea, Checkbox, Radio, and Upload using InputFile. For other input components, please use native html elements instead, and contributions are also welcome.
  2. Since the EditForm is encapsulated inside the Form component, So the Antiforgery will be the default enabled, To cancel, please refer to the documentation.
expand code expand code

There are three layout for form: horizontal, vertical, inline.

expand code expand code

Switch required or optional style with RequiredMark.

expand code expand code

Set component size, only works for antd components.

expand code expand code

This demonstrates the use of multiple elements within a FormItem.

Three typical scenarios are shown here.

  • Username: there is a description text or other component behind the input box, within FormItem only the component that uses @bind-Value will be bound to the FormItem, other components can be added at will.
  • Address: there are two controls, use two <FormItem NoStyle /> within the FormItem to bind the corresponding controls separately (only one control with @bind-Value can appear under a FormItem), use NoStyle for the FormItem, then The Grid layout of the FormItem will be ignored, even if LabelCol or WrapperCol is actively used.

The scenario also shows complex types of form validation. The Address property is a type that contains two properties. When a cascading form entry binds its property, it inherits all attributes of that property, but because the form does not bind this property, the external form cannot obtain Required and Label.

  • BirthDate: there are two inline controls with error messages displayed under each control, using two <FormItem />s to bind the corresponding controls separately, and modifying the style to make the layout inline.

For a more complex way of wrapping and reusing controls see Custom Form Controls below.

expand code expand code

Customized or third-party form controls can be used in Form, too. Controls must follow these conventions:

  • Inherits AntInputComponentBase
  • Assign value to [CurrentValue] instead of [Value]([CurrentValue] and [Value] are from AntInputComponentBase)

Price:

public class Price
{
    public int Number { get; set; }
    public string Currency { get; set; }
}

PriceInput.razor:

@namespace AntDesign.Docs
@inherits AntInputComponentBase<Price>

<span>
    <Input @bind-Value="@Value.Number"
           style="width: 100px" />
  
    <RadioGroup @bind-Value="@Value.Currency"
                style="width: 280px; margin: 0 8px">
        <Radio RadioButton Value=@("rmb")>RMB</Radio>
        <Radio RadioButton Value=@("dollar")>Dollar</Radio>
    </RadioGroup>
</span>
expand code expand code

Support using table as form component and validate cell edit.

expand code expand code

Check if the form has been modified by using IForm.IsModified.

expand code expand code

Setting a custom validator using the Form Validator property or the <Validator> element overrides the built-in validator. When validation is not required, it can be set to NULL to improve performance.

Note: When using the <Validator> element to set the validator, you need to wrap the other components within the Form with <ChildContent>.

For custom validator development, see document: ASP.NET Core Blazor forms and validation - Validator components

expand code expand code

Default will try to get the error message templates from the built-in globalization resource file,, which can be replaced by the Locale parameter. It can also be modified by the ErrorMessage of the data declaration feature and the Message of the Rules parameter.

Otherwise, also supports the DataAnnotations localization of Blazor forms. When FormItem.Label is not specified, it is automatically obtained from DisplayAttribute or DisplayNameAttribute.

expand code expand code

Use FormProvider to process data between forms. In this case, submit button is in the Modal which is out of Form. You can use form.Submit to submit form. Besides, we recommend native <Button HtmlType="submit" /> to submit a form.

expand code expand code

Use FormItem.Name to binding model properties dynamically, supporting both object and dictionary models.

expand code expand code

If you bind a dictionary, you don't have to define properties in advance, so you can easily implement dynamic forms.

expand code expand code

FormItem can be automatically generated by the 'TModel' type. currently supports automatic generation for string, DateTime, number, and enum type members. Whether a member is required or not is controlled based on its nullability.

Notice: This feature is in iteration, and incompatible changes may occur in subsequent releases.

expand code expand code

(v0.5+) Validation is turned off by default for performance reasons. Validate only when form.Validate () is called. It would be enabled by setting the 'ValidateOnChange' parameter.

expand code expand code

Form validation mode, including: default, Rules, mixed.

You can use the Rules mode to attach validationAttributes directly to the FormItem, Applicable scenario: The model class needs to be reused, but different pages have different validation Rules. The Rules mode can avoid creating multiple similar model classes repeatedly

expand code expand code

Perform different check rules according to different situations.

expand code expand code

We provide properties like validateStatus help hasFeedback to customize your own validate status and message, without using Form.

  1. validateStatus: validate status of form components which could be 'success', 'warning', 'error', 'validating'.
  2. hasFeedback: display feed icon of input control
  3. help: display validate message.
expand code expand code

Show field level error indicator if a field is invalid. This indicator will show when the form validates.

expand code expand code

You can set validation messages at any time.

expand code expand code

Form API#

Property Description Type Default Value
RequiredMark ParameterChange how required/optional field labels are displayed on the form.
  • Required - Will mark required fields
  • Optional - Will mark optional fields
  • None - Will mark no fields, regardless of required/optional
FormRequiredMark --
Layout ParameterLayout of form items in the form String FormLayout.Horizontal
ChildContent ParameterContent of the form. Typically contains different form inputs and layout elements. RenderFragment<TModel> --
LabelCol ParameterControl the layout of the label. Commonly used to set widths for different screen sizes. ColLayoutParam --
LabelAlign ParameterAlign the label to the left or right AntLabelAlignType? --
LabelColSpan ParameterGets/sets the Span property on AntDesign.Form`1.LabelCol. OneOf<String, Int32> --
LabelColOffset ParameterGets/sets the Offset property on AntDesign.Form`1.LabelCol. OneOf<String, Int32> --
WrapperCol ParameterControl the layout of the input element's wrapper. Commonly used to set widths for different screen sizes. ColLayoutParam --
WrapperColSpan ParameterGets/sets the Span property on AntDesign.Form`1.WrapperCol. OneOf<String, Int32> --
WrapperColOffset ParameterGets/sets the Offset property on AntDesign.Form`1.WrapperColOffset. OneOf<String, Int32> --
Size ParameterThe size of the ant components inside the form String --
Name ParameterGets or sets the form handler name. This is required for posting it to a server-side endpoint. Or using for get the form instance from FormProviderFinishEventArgs. String --
Method ParameterHttp method used to submit form String --
Model ParameterThe model to bind the form inputs to TModel --
Loading ParameterIf the form is loading or not Boolean false
OnFinish ParameterCallback executed when the form is submitted and PASSES validation. EventCallback<EditContext> --
OnFinishFailed ParameterCallback executed when the form is submitted and FAILS validation. EventCallback<EditContext> --
OnFieldChanged ParameterCallback executed when a field inside the form changes EventCallback<FieldChangedEventArgs> --
OnValidationRequested ParameterCallback executed when validation is requested EventCallback<ValidationRequestedEventArgs> --
OnValidationStateChanged ParameterCallback executed when the validation changes EventCallback<ValidationStateChangedEventArgs> --
Validator ParameterValidator to use in the form. Used when AntDesign.Form`1.ValidateMode is FormValidateMode.Default or FormValidateMode.Complex RenderFragment --
ValidateOnChange ParameterEnable validation when component values change Boolean --
ValidateMode ParameterWhich mode of validation the form should useWill use both attributes and rules in the same time.

Obsolete Will be removed in a future version.
FormValidateMode FormValidateMode.Complex
Enhance ParameterIf enabled, form submission is performed without fully reloading the page. This is equivalent to adding data-enhance to the form. Boolean --
Autocomplete ParameterWhether input elements can by default have their values automatically completed by the browser String --
Locale ParameterThe localization options FormLocale --
IsModified A flag indicating if the form has been modified Boolean --
EditContext Get the AntDesign.Form`1.EditContext instance inner the form EditContext --
Id ParameterID for the component's HTML String Uniquely Generated ID
Class ParameterSpecifies one or more class names for an DOM element. String --
Style ParameterSpecifies an inline style for a DOM element. String --
RefBack ParameterA ForwardRef instance. You can get a reference to the internal DOM by using AntDesign.ForwardRef.Current. ForwardRef --
Method Signature Return Type Description
Reset() void Reset all the values in the form
Submit() void Submit the form. Will trigger validation and either AntDesign.Form`1.OnFinish or AntDesign.Form`1.OnFinishFailed.
Validate() Boolean Execute validation
ValidationReset() void Reset validation
SetValidationMessages(String field, String[] errorMessages) void Set validation messages to a specific field.

FormValidateMode API#

Underlying Type: Int32

Name Description
Default Validation will come from data attributes on the model provided to AntDesign.Form`1.Model
Rules Validation will come from rules on FormItems in the form
Complex Use both Default mode and Rules mode

FormItem API#

Property Description Type Default Value
Name ParameterSpecific the name of the form item. It also can used as the Member Path for binding the property of the Model. String --
ChildContent ParameterContent for the form item. Typically will contain one of the input elements RenderFragment --
Label ParameterCustom label for the item. If neither AntDesign.FormItem.Label or AntDesign.FormItem.LabelTemplate are provided, the DisplayName attribute value or field name will be used (in that order). String --
LabelTemplate ParameterCustom label content for the item. Takes priority over AntDesign.FormItem.Label. If neither AntDesign.FormItem.Label or AntDesign.FormItem.LabelTemplate are provided, the DisplayName attribute value or field name will be used (in that order). RenderFragment --
LabelCol ParameterControl the layout of the label. Commonly used to set widths for different screen sizes. ColLayoutParam --
LabelAlign ParameterAlign the label to the left or right AntLabelAlignType? --
LabelColSpan ParameterGets/sets the Span property on AntDesign.FormItem.LabelCol. OneOf<String, Int32> --
LabelColOffset ParameterGets/sets the Offset property on AntDesign.FormItem.LabelCol. OneOf<String, Int32> --
WrapperCol ParameterControl the layout of the input element's wrapper. Commonly used to set widths for different screen sizes. ColLayoutParam --
WrapperColSpan ParameterGets/sets the Span property on AntDesign.FormItem.WrapperCol. OneOf<String, Int32> --
WrapperColOffset ParameterGets/sets the Offset property on AntDesign.FormItem.WrapperColOffset. OneOf<String, Int32> --
NoStyle ParameterNo style when true, it is used as a pure field control Boolean --
Required ParameterMark this item as required for validation purposes Boolean --
LabelStyle ParameterStyle that will only be applied to label element. Will not be applied if LabelTemplate is set. String --
Rules ParameterValidation rules to apply to this item FormValidationRule[] --
HasFeedback ParameterUsed in conjunction with AntDesign.FormItem.ValidateStatus to display the verification status icon. It is recommended to use it only with the Input component Boolean --
ShowFeedbackOnError ParameterWhether to show feedback icon on error. If set to false, it will not show the icon even if the field is in error state. Boolean --
ValidateStatus ParameterValidation status, if not set, it will be automatically generated according to validation rules FormValidateStatus --
Help ParameterPrompt information String --
ToolTip ParameterFormItem Help Tooltip information String --
Id ParameterID for the component's HTML String Uniquely Generated ID
Class ParameterSpecifies one or more class names for an DOM element. String --
Style ParameterSpecifies an inline style for a DOM element. String --
RefBack ParameterA ForwardRef instance. You can get a reference to the internal DOM by using AntDesign.ForwardRef.Current. ForwardRef --

FormValidationRule API#

Property Description Type Default Value
Len Validate the length. Valid AntDesign.FormValidationRule.Types: String, Number, or Array. Decimal? --
Min Validate length is greater than or equal to this number. Valid AntDesign.FormValidationRule.Types: String, Number or Array. Decimal? --
Max Validate length is less than or equal to this number. Valid AntDesign.FormValidationRule.Types: String, Number, or Array. Decimal? --
Required Make a field required Boolean? --
Pattern Validate the value passes a regular expression pattern String --
Message Custom error message. Will be auto generated if not provided. String --
Range Validate the value is in the specified range ValueTuple<Double, Double?? --
DefaultField Validate rule for all array elements. Valid AntDesign.FormValidationRule.Types: Array. (FormItem not supported now) FormValidationRule --
OneOf Whether the value is in specified values Object[] --
Enum Validate the value is in specified enum type. Type --
Fields Validate rule for child elements. Valid AntDesign.FormValidationRule.Types: Array, Object (FormItem not supported now) Dictionary<Object, FormValidationRule> --
Validator Custom validation function Func<FormValidationContext, ValidationResult> --
Transform Transformation function called before validation executes. The return value will have the validation ran against it. Func<Object, Object> --
Type Type of form field. See FormFieldType for all possible values. FormFieldType? --
ValidationAttribute Validate the value using the specified attribute. ValidationAttribute --

FormValidateErrorMessages API#

Property Description Type Default Value
Default Default generic validation error message String --
Required Default validation message for the Required rule String --
Enum Default validation message for the Enum rule String --
Whitespace Default validation message for the Whitespace rule String --
Date Messages for date type DateMessage --
Types Messages for when a field's type does not match the expected type TypesMessage --
String Messages for string type CompareMessage --
Number Messages for string type CompareMessage --
Array Messages for array type CompareMessage --
Pattern Messages for the Pattern validation rule PatternMessage --
DatePicker Input
文档已更新,请点击 此处 更新。
A new version of this app is available. Click here to update.