Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Form): optimize default behavior, add demos and update docs #2084

Merged
merged 2 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions docs/Masa.Blazor.Docs/Examples/components/forms/AutoLabel.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
@using System.ComponentModel.DataAnnotations
@using System.ComponentModel

<MForm Model="_model"
AutoLabel
Class="mx-auto"
Style="width: 360px">
<MTextField @bind-Value="_model.Name" Filled>
</MTextField>
<MSelect @bind-Value="_model.Item"
Items="@_sports"
Filled
ItemText="u => u"
ItemValue="u => u">
</MSelect>
<MButton Type="submit" Block Color="primary">Submit</MButton>

@* <Masa.Blazor.Components.Form.AutoLabelOptions AttributeType="@typeof(DisplayAttribute)"/> *@
</MForm>

@code {

class Model
{
[Display(Name = "Username")]
[Required]
[MaxLength(10, ErrorMessage = "Name must be less than 10 characters")]
public string Name { get; set; }

[Display(Name = "Favorite sport")]
[Required] public string Item { get; set; }
}

private bool _valid = true;
private Model _model = new();

List<string> _sports = new()
{
"Basketball",
"Football",
"Tennis",
"Swimming"
};

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,17 @@

private class Model
{
[DisplayName("enableI18n-demo.name")]
[Display(Name = "enableI18n-demo.name")]
[Required(ErrorMessage = "enableI18n-demo.required")]
[MaxLength(10, ErrorMessage = "enableI18n-demo.maxlength-10")]
public string? Name { get; set; }

[DisplayName("enableI18n-demo.email")]
[Display(Name = "enableI18n-demo.email")]
[Required(ErrorMessage = "enableI18n-demo.required")]
[EmailAddress(ErrorMessage = "enableI18n-demo.invalid-email")]
public string? Email { get; set; }

[DisplayName("enableI18n-demo.item")]
[Display(Name = "enableI18n-demo.item")]
[Required(ErrorMessage = "enableI18n-demo.required")]
public string? Item { get; set; }

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
@using System.ComponentModel.DataAnnotations
@using System.ComponentModel

<div style="width: 360px;" class="mx-auto">
<MRadioGroup @bind-Value="@_validateOn" HideDetails="true" Label="Validate On">
<MRadio Value="ValidateOn.Input" Label="On input"></MRadio>
<MRadio Value="ValidateOn.Blur" Label="On blur"></MRadio>
<MRadio Value="ValidateOn.Submit" Label="On submit"></MRadio>
</MRadioGroup>

<MDivider Class="my-2" />

<MForm Model="_model"
ValidateOn="_validateOn"
AutoLabel>
<MTextField @bind-Value="_model.Name" Filled
Hint="Least 5 characters"
PersistentHint>
</MTextField>
<MSelect @bind-Value="_model.Item"
Items="@_sports"
Filled
ItemText="u => u"
ItemValue="u => u">
</MSelect>
<MSlider @bind-Value="_model.Age" ThumbLabel="@("always")"></MSlider>
<MButton Type="submit" Block Color="primary">Submit</MButton>
</MForm>
</div>
@code {

class Model
{
[Display(Name = "Username")]
[Required]
[MinLength(5)]
public string Name { get; set; }

[Display(Name = "Favorite sport")]
[Required] public string Item { get; set; }

[Display(Name = "Age")]
[Range(18, 60)]
public int Age { get; set; }
}

private bool _valid = true;
private Model _model = new();
private ValidateOn _validateOn;

List<string> _sports = new()
{
"Basketball",
"Football",
"Tennis",
"Swimming"
};

}
1 change: 0 additions & 1 deletion docs/Masa.Blazor.Docs/Masa.Blazor.Docs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<PackageReference Include="Microsoft.AspNetCore.Components" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.CustomElements" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" Version="3.2.0-rc1.20223.4" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"enableValidation": "Enable form validation.",
"model": "Objects that require form validation.",
"readonly": "",
"value": "Whether the verification is successful."
"value": "Whether the verification is successful.",
"autoLabel": "Whether to automatically generate labels for form items.",
"validateOn": "Validation timing, options: input, blur, submit."
},
"events": {
"onInvalidSubmit": "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"enableValidation": "开启表单校验",
"model": "需要表单校验的对象",
"readonly": "",
"value": "是否校验成功"
"value": "是否校验成功",
"validateOn": "校验时机,可选输入时验证、失去光标时验证和提交时验证",
"autoLabel": "是否自动添加标签"
},
"events": {
"onInvalidSubmit": "",
Expand Down
33 changes: 18 additions & 15 deletions docs/Masa.Blazor.Docs/wwwroot/pages/components/forms/en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ Rules allow you to apply custom validation on all form components. These are ver

<masa-example file="Examples.components.forms.Rules"></masa-example>

#### Auto label {released-on=v1.7.0}

When `AutoLabel` is `true`, **MForm** will automatically get the value of the `[Display]` or `[DisplayName]` attribute of the form field as the label.
By default, it resolves the `[Display]` attribute, and you can also configure the `AttributeType` to resolve the `[DisplayName]` attribute by setting the `Masa.Blazor.Components.Form.AutoLabelOptions` subcomponent.

<masa-example file="Examples.components.forms.AutoLabel"></masa-example>

#### Validate on {released-on=v1.7.0}

The `ValidateOn` prop is used to specify when to validate the form, with optional values of `Input`, `Blur` and `Submit`.

<masa-example file="Examples.components.forms.ValidateOnDemo"></masa-example>

### Misc

#### Model validation
Expand All @@ -37,39 +50,29 @@ Validate a single field using the `Validate` method of the **MForm** instance.

<masa-example file="Examples.components.forms.ValidateField"></masa-example>

#### Validation with submit and clear {updated-in=v1.6.0}
#### Submit and clear {#submit-and-clear updated-in=v1.6.0}

You can use the methods provided by `Context` in the content of **MForm**, or use the component instance provided by `@ref` outside of **MForm**.

<masa-example file="Examples.components.forms.ValidationWithSubmitAndClear"></masa-example>

#### Enable I18n {updated-in=v1.6.0}
#### DataAnnotations with I18n {#enable-i18n updated-in=v1.6.0}

Enable [I18n](/blazor/features/internationalization) to support multilingual validation messages. Locale resources used in the example can be found in [GitHub](https://github.com/masastack/MASA.Blazor/blob/0f4a450479bceb816d58bbbb7b8f8ca7655e2f94/docs/Masa.Docs.Shared/wwwroot/locale/en-US.json#L128).

<app-alert type="warning" content="Cannot be applied to [complex types](#validate-complex-type-with-dataannotations), and only support localization for property names with an index of `0`, such as error messages for `[Range]` may not be localized correctly. Therefore, it is recommended to use FluentValidation or use additional *Resources.resx* for localization."></app-alert>
<app-alert type="warning" content="Only support localization for property names with an index of `0`, such as error messages for `[Range]` may not be localized correctly."></app-alert>

<masa-example file="Examples.components.forms.EnableI18n"></masa-example>

#### Validate complex type with DataAnnotations

Use `[ValidateComplexType]` attribute and `<ObjectGraphDataAnnotationsValidator />` to validate complex types.

```xml Project.csproj
<PackageReference Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" Version="3.2.0-rc1.20223.4" />
```

<masa-example file="Examples.components.forms.ValidateComplexType"></masa-example>

#### Validate with FluentValidation
#### Validate with FluentValidation {#fluent-validation}

<app-alert type="warning" content="Validators need to be registered, see [FluentValidation Dependency Injection](https://docs.fluentvalidation.net/en/latest/di.html) for details."></app-alert>

**MForm** supports FluentValidation validation.

<masa-example file="Examples.components.forms.ValidateWithFluentValidation"></masa-example>

#### Parse external validation result
#### Parse external validation result {#parse-form-validation}

**MForm** supports parsing of `ValidationResult` , which users can use as `FormContext.ParseFormValidation' parameter that displays the validation results in a front-end form, using the validation collection as an example.

Expand Down
49 changes: 26 additions & 23 deletions docs/Masa.Blazor.Docs/wwwroot/pages/components/forms/zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,69 +7,72 @@ related:
- /blazor/components/text-fields
---

## 使用
## 使用 {#usage}

内部的 **MForm** 组件可以很容易地向表单输入添加验证。所有输入组件都有一个 `Rules` 参数,该参数接受类型为 `Func<string?, StringBoolean>` 的列表。这允许您指定输入有效或无效的条件。每当输入值改变时,数组中的每个函数都会收到一个新值,并且每个数组元素都会被评分。如果函数或数组元素返回 `false` 或 `string`,表示验证失败,则将字符串值显示为错误消息。

<masa-example file="Examples.components.forms.Usage"></masa-example>

## 示例
## 示例 {#examples}

### 属性
### 属性 {#props}

#### 规则
#### 规则 {#rules}

规则允许您对所有表单组件应用自定义验证。这些是按顺序验证的,一次最多显示 1 个错误,因此请确保相应地对规则进行排序。

<masa-example file="Examples.components.forms.Rules"></masa-example>

### 其他
#### 自动标签 {#auto-label released-on=v1.7.0}

#### 模型验证
当 `AutoLabel` 为 `true` 时,**MForm** 会自动获取表单对象字段的 `[Display]` 或 `[DisplayName]` 特性的值作为 Label。
默认解析 `[Display]` attribute,也可以通过 `Masa.Blazor.Components.Form.AutoLabelOptions` 子组件配置 `AttributeType` 为 `typeof(DisplayNameAttribute)` 解析 `[DisplayName]` attribute。

<masa-example file="Examples.components.forms.AutoLabel"></masa-example>

#### 验证时机 {#validate-on released-on=v1.7.0}

`ValidateOn` 属性用于指定何时验证表单,可选值为 `Input`,`Blur` 和 `Submit`。

<masa-example file="Examples.components.forms.ValidateOnDemo"></masa-example>

### 其他 {#misc}

#### 模型验证 {#model-validation}

除了在每个输入组件上通过 `Rules` 属性进行验证之外,还可以对单个对象模型进行验证。

<masa-example file="Examples.components.forms.Validation"></masa-example>

#### 验证单个字段 {released-on=v1.6.0}
#### 验证单个字段 {#validate-single-field released-on=v1.6.0}

使用**MForm**实例的`Validate`方法验证单个字段。
使用 **MForm** 实例的 `Validate` 方法验证单个字段。

<masa-example file="Examples.components.forms.ValidateField"></masa-example>

#### 通过提交和清除进行验证 {updated-in=v1.6.0}
#### 通过提交和清除进行验证 {#submit-and-clear updated-in=v1.6.0}

在 **MForm** 的内容里可以使用 `Context` 提供的方法,在 **MForm** 外部可以使用 `@ref` 拿到组件实例提供的方法。

<masa-example file="Examples.components.forms.ValidationWithSubmitAndClear"></masa-example>

#### 启用 I18n {updated-in=v1.6.0}
#### DataAnnotations 本地化 {#enable-i18n updated-in=v1.7.0}

通过 `EnableI18n` 属性启用 [I18n](/blazor/features/internationalization) 以支持验证信息多语言。示例使用的本地话资源你能在 [GitHub](https://github.com/masastack/MASA.Blazor/blob/0f4a450479bceb816d58bbbb7b8f8ca7655e2f94/docs/Masa.Docs.Shared/wwwroot/locale/zh-CN.json#L129) 中找到。

<app-alert type="warning" content="无法作用于[复杂类型](#section-901a8fc7-dataannotations-9a8c8bc1590d67427c7b578b),并且只支持索引为`0`的属性名的本地化,例如`[Range]`的错误信息可能不会被正确本地化。因此推荐使用FluentValidation或者使用额外的*Resources.resx*应用本地化。"></app-alert>
<app-alert type="warning" content="只支持索引为`0`的属性名的本地化,例如`[Range]`的错误信息无法解析`Min`和`Max`。"></app-alert>

<masa-example file="Examples.components.forms.EnableI18n"></masa-example>

#### 通过 DataAnnotations 验证复杂类型

使用 `[ValidateComplexType]` 属性和 `<ObjectGraphDataAnnotationsValidator />`,可以验证复杂类型。

```xml Project.csproj
<PackageReference Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" Version="3.2.0-rc1.20223.4" />
```

<masa-example file="Examples.components.forms.ValidateComplexType"></masa-example>

#### 使用 FluentValidation 验证
#### 使用 FluentValidation 验证 {#fluent-validation}

**MForm** 支持 **FluentValidation** 验证。

<app-alert type="warning" content="验证器需要注册,详情请查看 [FluentValidation Dependency Injection](https://docs.fluentvalidation.net/en/latest/di.html)。"></app-alert>

<masa-example file="Examples.components.forms.ValidateWithFluentValidation"></masa-example>

#### 解析外部验证结果
#### 解析外部验证结果 {#parse-form-validation}

**MForm** 支持解析 `ValidationResult`,用户可以将服务端表单验证返回的 `ValidationResult` 作为 `FormContext.ParseFormValidation` 的参数,将验证结果在前端表单展示,以验证集合为示例。

Expand Down
Loading
Loading