此示例展示了如何进行内联字段验证,在本例中是电子邮件地址。为此,我们需要创建一个带有输入的表单,该表单将要验证的值 POST
返回到服务器并使用验证结果更新 DOM。
¥This example shows how to do inline field validation, in this case of an email address. To do this
we need to create a form with an input that POST
s back to the server with the value to be validated
and updates the DOM with the validation results.
我们从这个表格开始:
¥We start with this form:
<h3>Signup Form</h3>
<form hx-post="/contact">
<div hx-target="this" hx-swap="outerHTML">
<label>Email Address</label>
<input name="email" hx-post="/contact/email" hx-indicator="#ind">
<img id="ind" src="/img/bars.svg" class="htmx-indicator"/>
</div>
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lastName">
</div>
<button class="btn primary">Submit</button>
</form>
请注意,表单中的第一个 div 已将自身设置为请求的目标,并指定了 outerHTML
交换策略,因此它将完全被响应替换。然后,输入指定当 changed
事件发生时它将 POST
到 /contact/email
进行验证(这是输入的默认值)。它还为请求指定了一个指示器。
¥Note that the first div in the form has set itself as the target of the request and specified the outerHTML
swap strategy, so it will be replaced entirely by the response. The input then specifies that it will
POST
to /contact/email
for validation, when the changed
event occurs (this is the default for inputs).
It also specifies an indicator for the request.
当发生请求时,它将返回一个部分来替换外部 div。它可能看起来像这样:
¥When a request occurs, it will return a partial to replace the outer div. It might look like this:
<div hx-target="this" hx-swap="outerHTML" class="error">
<label>Email Address</label>
<input name="email" hx-post="/contact/email" hx-indicator="#ind" value="test@foo.com">
<img id="ind" src="/img/bars.svg" class="htmx-indicator"/>
<div class='error-message'>That email is already taken. Please enter another email.</div>
</div>
请注意,此 div 用 error
类注释,并包含错误消息元素。
¥Note that this div is annotated with the error
class and includes an error message element.
此表单可以使用以下 CSS 轻松设置样式:
¥This form can be lightly styled with this CSS:
.error-message {
color:red;
}
.error input {
box-shadow: 0 0 3px #CC0000;
}
.valid input {
box-shadow: 0 0 3px #36cc00;
}
提供更好的视觉反馈。
¥To give better visual feedback.
下面是此示例的工作演示。唯一可接受的电子邮件是 test@test.com
。
¥Below is a working demo of this example. The only email that will be accepted is test@test.com
.