目前,我对可能显示错误消息的每个字段执行类似的操作:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:choose>
<c:when test="${message == null}">
<label>Field name</label>
<input type="text" name="field-name">
</c:when>
<c:otherwise>
<label class="error">Field name</label>
<input type="text" name="field-name">
<small class="error">${message}</small>
</c:otherwise>
</c:choose>
如何干燥/改进这段代码?我不想每次在其他领域需要时都重复所有这些内容。
最佳答案
看看你在重复什么,然后统一它。您正在重复<label>
和 <input>
元素。只需向他们展示一次。你只需要在<label>
中添加一个类即可以及有消息时的附加元素。
<label class="${not empty message ? 'error' : ''}">Field name</label>
<input type="text" name="field-name">
<c:if test="${not empty message}"><small class="error">${message}</small></c:if>
您甚至可以省略 <c:if>
总之,如果没有消息,那么<small>
根本不会以任何方式出现在用户界面中。
<label class="${not empty message ? 'error' : ''}">Field name</label>
<input type="text" name="field-name">
<small class="error">${message}</small>
我只会使用 <span>
而不是<small>
因为不鼓励将后者用于此目的。
<label class="${not empty message ? 'error' : ''}">Field name</label>
<input type="text" name="field-name">
<span class="error">${message}</span>
关于java - 如何在 JSP/Servlet 中执行表单验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12035354/