是否可以在此JSP表单上使用JavaScript进行验证?

时间:2017-04-06 07:50:21

标签: javascript forms validation jsp

想要验证此JSP表单

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>

我试过这个但不会工作,我做错了什么?

的JavaScript

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;
    }
}

提前致谢

1 个答案:

答案 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>