shilpa shilpa - 7 months ago 11
HTML Question

When found blank space at the start or end of text box populate alert message in jsp

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.

Answer
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.

Comments