Angular表单验证通过后如何在输入控件右上角显示绿色对勾图标
Angular 邮箱输入框验证通过后显示右上角绿色对勾实现方案
你现有代码有两个基础问题需要先修正:
- 输入框的
is-invalid类绑定的是f['password'].errors,和你要验证的useremail控件不匹配,状态判断逻辑本身就不对 - 提示图标直接放在input同级,没有定位上下文,没法固定到输入框内部右上角
不用找Bootstrap现成的封装类,几行代码就能实现,完全符合Bootstrap的表单风格:
调整后的代码实现
HTML结构
<label for="useremail">User E-mail</label> <!-- 父容器加相对定位,作为内部图标的定位基准 --> <div class="position-relative"> <input type="email" formControlName="useremail" class="form-control pe-4" [ngClass]="{ 'is-invalid': submitted && f['useremail'].errors, 'is-valid': submitted && !f['useremail'].errors }" /> <!-- 验证通过绿色对勾 --> <span *ngIf="submitted && !f['useremail'].errors" class="position-absolute top-0 end-0 text-success mt-2 me-2" > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"> <path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425a.247.247 0 0 1 .02-.022Z"/> </svg> </span> <!-- 验证失败红色叉号 --> <span *ngIf="submitted && f['useremail'].errors" class="position-absolute top-0 end-0 text-danger mt-2 me-2" > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"> <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/> </svg> </span> </div>
实现说明
- 所有定位、颜色类全是Bootstrap自带工具类,不需要写额外自定义CSS:
position-relative给输入框父容器加定位上下文position-absolute top-0 end-0把图标固定到容器右上角mt-2 me-2微调图标边距,刚好落在输入框内部右上角位置text-success/text-danger直接用Bootstrap默认的成功绿、错误红,和原生表单状态样式统一- 给输入框加
pe-4(右侧内边距),避免输入的文字和右上角图标重叠
- 修正了原代码的验证逻辑错误:状态判断直接绑定
useremail控件本身的错误状态,不会被其他表单控件(比如你原来写的password)的状态影响 - 图标用Bootstrap内置的内联SVG,不需要额外引入第三方图标库,没有兼容问题
如果是Bootstrap 4版本没有内置SVG图标,直接把SVG替换成Unicode字符
✓/✕,给span加fw-bold类加粗,效果完全一致。
内容的提问来源于stack exchange,提问作者janci
相关产品推荐
相关产品推荐

