0

I am trying to validate a form with couple of fields. In one field I have to validate email id, if the elements of the email ArrayList exist. Can anyone tell me where I'm doing wrong? Any solution or other way around? Thanks.

Here is JSP snippet where I'm getting all elements into ArrayList.

<%
    ArrayList userEmails = getAllEmails();

//For test only. Its printing all Emails
     for(Object email : userEmails)
        System.out.println("Email: " + email);

   request.setAttribute("userEmails", userEmails);
%>

Here is the JavaScript snippet:

<script type="text/javascript">
    $.validator.addMethod('emailExist', function (value, element) {
        <c:forEach var="email" items="${userEmails}">
        return this.optional(element) || ${email}.test(value);
        </c:forEach>
    }, "Email already exist");

var validator = $('#EditUser').validate({
rules: {
          Email: {
            required: true,
            email: true
          },
    ... more fields
</script>

I can see following error messages but I also want to see "Email already exist".

Message for invalid email Message for empty field

Now, when I changed the above code (emailExist method) like this:

$.validator.addMethod('emailExist', function (value, element) {
        <c:set var="userEmail" value="${value}"/>
        <c:forEach var="email" items="${userEmails}">
        <c:if test="${email eq userEmail}">
        return this.optional(element) || ${email}.test(value);
        </c:if>
        </c:forEach>
    }, "Email already exist");

Now the "Email already exist" message shows always, even its not exist. Even the message chages even entered a letter:

always shows exist message

Here is HTML snippet:

<input type="email" id="Email" name="Email"class="required emailExist form-control">
Sadequer Rahman
  • 133
  • 5
  • 11

2 Answers2

1

The Issue:

You are mixing client side and server side code. JavaScript and JavaServer Pages are executed separately.

  • JSP code is compiled on the server,
  • The result is a HTML, that is delivered to the browser
  • In the browser the JavaScript is executed

So JSP related stuff like:

  • JSTL, JSP Standard Tag Library (tags like <jsp:something> <c:something>)
  • JSP-EL, Expression Language (strings like ${something})

is processed on the server.

You can see, what HTML code is received in browser, by pressing Ctrl+U in Firefox/Chrome.
So you can examine, the generated HTML and JavaScript.

In the second line of the code you try to access a JavaScript parameter value with a serverside Expression Language ${value}:

$.validator.addMethod('emailExist', function (value, element) {
    <c:set var="userEmail" value="${value}"/>
    <c:forEach var="email" items="${userEmails}">

This will not work.

Theoretical Solution (but please don't do it):

You can theoretically generate an Javascript-Array on the serverside, and than validate on the client side with Javascript. But this will be dirty!
What will happen when you have thousands or millions of registered users?! It will be messy. And a privacy exposure.

Practical Solution:

A better validation approach, could be to make an AJAX validation request, and let the server decide, if the email is already taken or not.

You can read more here: How to use Servlets and Ajax?

Community
  • 1
  • 1
code_angel
  • 1,537
  • 1
  • 11
  • 21
  • thanks for your reply. You have a valid practical solution. After I read your provided article, I am trying to solve my problem. If you come across any other proven solution to solve this problem, highly appreciated for your help. Again, thanks for your time. – Sadequer Rahman Dec 19 '16 at 15:11
0

As @code_angel mentioned about Practical Solution. If anyone needed it, here is the tested working solution:

On Servlet page:

private void isEmailExists(String checkEmail, String userStatus, String dbUID, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        ArrayList userEmails = getAllEmails();
        boolean emailNotExists = true;
        if(userStatus.contains("Edit")){
            Hashtable userHash = getSystemUserDetails(dbUID);
            String userEmail = cvtStr(userHash.get("LoginEmail"));
            if(userEmail.equals(checkEmail)) {
                response.getWriter().write(String.valueOf(emailNotExists));
                return;
            }
        }

        for(Object email : userEmails){
            if(email.equals(checkEmail)){
                emailNotExists = false;
                break;
            }
        }
        response.getWriter().write(String.valueOf(emailNotExists));
    }

On JavaScript:

var validator = $('#EditUser').validate({
        rules: {
            LoginEmail: {
                required: true,
                email: true,
                remote: {
                    url: "/servlet/UserServlet",
                    type: "POST",
                    data: {
                        dbUIDEdit: function() {return $("#dbUID").val();}
                    }
                }
            },
//More fields
},
        messages: {
            LoginEmail: {
                required: 'Email address is required',
                email: 'Please enter a valid email address',
                remote: 'Email already exists'
            }
//More messages
});
Sadequer Rahman
  • 133
  • 5
  • 11