Member Avatar for Member #849081

Hi everyone,
Im new to web programming and i need some help, I have something like this:

<td><label>User (Login): </label></td>
    <td><input class="textbox" autofocus="true" type="text" maxLength="7" name="cUser" id="cUser" /></td>
</tr><tr></tr>
<td><label>First Name: </label></td>
    <td><input class="textbox" type="text" maxLength="20" name="cFname" id='cFname' value=""/></td>
</tr><tr></tr><tr>
<td><label>Last Name: </label></td>
    <td><input class="textbox" type="text" maxLength="30" name="cLName" id="cLName" /></td>
</tr><tr></tr>
<td><label>Password: </label></td>
    <td><input class="textbox" type="password" maxLength="15" name="cPass" id="cPass" /></td>
</tr><tr></tr>
.
.
.

I'm actually working in netbeans 7.0.1 using just .jsp and .java and using postgresql 9.1 as my DB. Already defines some .java to get the connection and other class to handle users.
What i'm trying to do here and i have no clue to do so, is to validate if the username is available and dont exist already in my DB. This is a new user register at a website im creating.
What should i do so the moment the user enter his username, and if it is not available show a message as an alert maybe that the user is not available and must choose another.

Please help

Dani AI

Generated

For : since the project is already JSP/Java + PostgreSQL, there is no need to switch to PHP. A common pattern (combining 's AJAX idea with server-side checking) is: debounce the username field in the browser, call a small servlet endpoint, let the servlet run a parameterized query and return a tiny JSON response. This gives instant feedback while keeping a definitive validation step on the server.

Server-side (Servlet / DAO): use a PreparedStatement and a lightweight query that stops at the first match. Prefer a pooled DataSource (JNDI or HikariCP) in production.

String username = req.getParameter("cUser");
try (Connection conn = ds.getConnection();
     PreparedStatement ps = conn.prepareStatement(
         "SELECT 1 FROM users WHERE username = ? LIMIT 1")) {
  ps.setString(1, username);
  try (ResultSet rs = ps.executeQuery()) {
    boolean available = !rs.next();
    resp.setContentType("application/json");
    resp.getWriter().write("{\"available\":" + available + "}");
  }
}

Client-side: debounce input, call the endpoint, and update the UI based on the JSON result.

const el = document.getElementById('cUser');
let timer;
el.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    fetch('/checkUsername?cUser=' + encodeURIComponent(el.value))
      .then(r => r.json())
      .then(j => { /* show "available" or "taken" message */ });
  }, 400);
});

Important cautions: always enforce a UNIQUE constraint on the username column in PostgreSQL and handle duplicate-key errors at insert time (Postgres SQLSTATE 23505) to avoid race conditions. Never build SQL by string concatenation; use parameterized queries. Use connection pooling for scalability and validate again on final form submit—AJAX is UX-only, server-side checks are authoritative.

Recommended Answers

All 3 Replies

What you have posted is HTML which isn't able to do much for you in terms of checking for user existance but the simplest way to do it (and shall be needed for things like adding the user to the database and logging in) is to use PHP and something like this:

$Username = $_POST['Username'];

mysql_connect ("localhost", "root", "Password");
mysql_select_db ("Database");

$UserCheck = mysql_query("SELECT * FROM Members WHERE Username = '$Username'");
$Count = mysql_num_rows($UserCheck);

if ($Count != 0)
{
    mysql_close();

    die ("User Exists");
}

Obviously this would need to go around with other code to make the registration work, but this basically opens up the database, and checks it against the form. If it comes back with a value other than 0 (ie. there is already a record with that username) then it displays an error message indicating that the username is already taken.

The only down side with this is you need to submit the form to see it, if you do use it MAKE SURE TO SANATIZE ALL INPUT!

Member Avatar for Member #849081

Got it, well i have to learn PHP since it seems to be the common way to do this. Thank you very much AHarrisGsy. By the way its working now so thank you again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.