想要验证此JSP表单
<form:form action="saveEmpleado" method="post" modelAttribute="empleado">
<table border="1" class="table-fill">
<form:hidden path="id"/>
<tr>
<td>Email:</td>
<td><form:input id="email" path="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input id="enviar" type="submit" value="Guardar"/></td>
</tr>
</table>
</form:form>
我试过这个但不会工作,我做错了什么?
window.onload = iniciar;
function iniciar() {
document.getElementById('enviar').addEventListener('click', validar, false);
}
function validar() {
validarEmail();
}
function validarEmail() {
var elemento = document.getElementById('email');
var regx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regx.test(elemento))) {
alert("Error");
return false;
}
}
提前致谢
答案 0 :(得分:1)
这里只需你可以在提交按钮上点击onclick功能。在if条件中有一个额外的括号( if (!regx.test(elemento)) )
JSP:
<form:form action="saveEmpleado" method="post" modelAttribute="empleado">
<table border="1" class="table-fill">
<form:hidden path="id"/>
<tr>
<td>Email:</td>
<td><form:input id="email" path="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input id="enviar" type="submit" value="Guardar" onclick="validarEmail();"/></td>
</tr>
</table>
</form:form>
Javascript:
<script>
function validarEmail() {
var elemento = document.getElementById('email');
var regx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regx.test(elemento)) {
alert("Error");
return false;
}
}
</script>