[英]HTML5 Validation in Blazor
我試圖讓內置的 HTML5 驗證在我的 Blazor 應用程序中工作,但它只是被忽略了。
這是我的 Razor 代碼
<form class="row">
<div class="form-row">
<label for="exampleFormControlInput1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com" @bind="@details.Email">
</div>
<div class="form-row">
<label for="exampleFormControlInput1" class="form-label">Phone</label>
<input type="tel" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com" @bind="@details.Phone">
</div>
<div class="form-row">
<button type="submit" class="btn btn-primary" @onclick="SubmitForm">Send</button>
</div>
</form>
</div>
@code {
private ContactDetails details = new ContactDetails();
public async void SubmitForm()
{
var result = await Http.PostAsJsonAsync("Contact", details);
}
}
我知道我可以使用 Blazors 驗證,但我只想為此使用內置的 HTML5 驗證,因為它是一種非常基本的形式。 如果觸發了 HTML5 驗證,如何停止運行 SubmitForm 代碼?
如果我從 SubmitForm() 方法中刪除代碼,當它進入該方法並返回到網頁時,顯然什么也沒有發生,並顯示 html5 驗證消息,但顯然該方法仍在被觸發。 如果出現 html5 驗證錯誤,是否有辦法停止代碼運行?
好的,我已經想出了如何做到這一點。
只需將事件添加並 onsubmit 到 Form 標簽,然后從按鈕中刪除 onclick。
<form class="row" @onsubmit="SubmitForm">
然后按預期工作。
Now there are clearly lots of benefits to using the built in Blazor forms components but sometimes just working with standard html forms is needed and thankfully there is a solution to do that.
通過使用@using System.Text.RegularExpressions 添加它來使用正則表達式;
有效email:komaei@live.com
無效郵箱:komaei, komaei@, komaei@live.c
<div class="form-group row">
<label for="@nameof(createModel.Email)" class="col-sm-2 col-form-label text-right">Email : </label>
<div class="col-lg-7 col-sm-10">
<InputText type="email" class="form-control" placeholder="Email" required
id="@nameof(createModel.Email)" @bind-Value="createModel.Email">
</InputText>
</div>
</div>
@code {
private Customer createModel = new();
private async Task SubmitForm()
{
var emailPattern = @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$";
Regex regex = new Regex(emailPattern);
if (regex.IsMatch(createModel.Email) == false)
{
await JsRuntime.InvokeVoidAsync("alert", "Email is not valid!");
return;
}
var response = await _http.PostAsJsonAsync("Customers/Create", createModel);
if (response.IsSuccessStatusCode) // 200
_navigationManager.NavigateTo("Customers");
else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
await JsRuntime.InvokeVoidAsync("alert", response.Content.ReadAsStringAsync().Result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.