0

I have one page in jsp which has one textbox and submit button. when i enter value in textbox and click on submit it is redirecting me to new page. But issue is i want to validate that textbox should not have any blank space at the start and end of value entered in text box. Below is the code which i am trying

<%
String Hostname=user2.getHost();
String Wrong=" "+Hostname+" ";
if (Hostname != null)
{
 if (Hostname == " "+Hostname+" ")
         {
        %>
        <div class="alert-box" > <span>Warning: </span>Not a valid hostname !! <% out.println("Hostname ='"+Hostname+"'"); %></div>
        <%

        }
else
{
pageContext.forward("InstanceList.jsp");
}


}
else
    {
        pageContext.include("NoHost.jsp");
    }
%>

I am trying below if statement. If found hostname with blank space at start or end it should give alert message but every time it is going in first else and running InstanceList.jsp

 if (Hostname == " "+Hostname+" ")

whereas first check of hostname null is working properly.

Please help if i am doing something wrong.

shilpa
  • 9
  • 1
  • 5

1 Answers1

0
if (Hostname == " "+Hostname+" ")

The above condition will never be true.

  1. You should not use == for string comparison but use .equals(Object object) method. Read here to know why.
  2. Also, Logically talking, even if you ignore (1) Your condition basically evaluates to

    if("abc" == " abc "). if Hostname is "abc" for example.

You need a condition like.

if ((Character.isWhitespace(Hostname.charAt(0)) || (Character.isWhiteSpace(Hostname.charAt(Hostname.length() - 1))){
// pop up here
}

The above will be true if Hostname starts or ends with a space. you can replace the || with an && if it should be true only if it starts and ends with a space

You might need to <%@ page import="java.lang.Character" %> on your page to include the Character Class.

Community
  • 1
  • 1
Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
  • above code was missing with some brackets i edited it as below: if ((Character.isWhitespace(Hostname.charAt(0))) || (Character.isWhiteSpace(Hostname.charAt(Hostname.length() - 1)))) But i am getting error as The method isWhiteSpace(char) is undefined for the type Character – shilpa Apr 29 '16 at 08:43
  • Ohh i found where it was wrong. It's isWhitespace, not isWhiteSpace i corrected it and now it is working fine. Thank you so much. – shilpa Apr 29 '16 at 08:49