如何使文本字段值唯一?

时间:2012-09-28 05:53:45

标签: javascript html database

我有一个带有文本字段的表单。我想使文本字段条目唯一,以便人们不能再次保存相同的名称。

我们可以在表格列中使该字段唯一吗?

我们如何编写JS代码以使该字段唯一?

这就是我在后端所做的事情。

public static boolean isUniqueShortName(String sname)
throws DataObjectException
{
    return isUniqueShortName(sname, null);
}


public static boolean isUniqueName(String sname, BigDecimal id)
throws DataObjectException
{

    final String SELECT_SQL = "SELECT COUNT(*) FROM LISTS WHERE LIST_NAME = ? AND ID <> ?";
    final String SELECT_SQL2 = "SELECT COUNT(*) FROM LISTS WHERE LIST_NAME = ?";

    boolean exists = false;
    Connection conn = DataObjectConnectionPool.getInstance().getConnection();
    PreparedStatement pstmt = null;
    ResultSet result = null;

    try
    {
        // determine SQL
        String SQL = null;
        if (list_id != null)
        {
            SQL = SELECT_SQL;
        }
        else
        {
            SQL = SELECT_SQL2;
        }

        // prepare statement
        pstmt = conn.prepareStatement(SQL);

        // set parameters
        pstmt.setString(1, sname);
        if (id != null)
        {
            pstmt.setBigDecimal(2, id);
        }

        // execute query
        result = pstmt.executeQuery();


        // fetch results
        while (result != null && result.next())
        {
            // fetch
            int count = result.getInt(1);
            exists = (count == 0);
        }

        // close results
        if (result != null)
        {
            try { result.close(); } catch (Exception e) {}
        }

        // close statement
        if (pstmt != null)
        {
            try { pstmt.close(); } catch (Exception e) {}
        }
    }
    catch (Exception ex)
{ 
// throw error
        throw new DataObjectException("Error checking for name uniqueness for " + sname);
    }
    finally
    {
        // close results
        if (result != null)
        {
            try { result.close(); } catch (Exception e) {}
        }

        // close statement
        if (pstmt != null)
        {
            try { pstmt.close(); } catch (Exception e) {}
        }


        // close connection
        if (conn != null)
        {
            try { conn.close(); } catch (Exception e) {}
        }
    }

    return exists;
}

2 个答案:

答案 0 :(得分:1)

您无法在客户端使该字段独一无二。您可以在服务器上进行验证,并说明客户端已存在该名称。

比如执行Ajax请求以查看名称是否存在。

让表列是一种方式,但你还需要查看索引的位置,如果它是一个长度很大的字符串,我建议你寻找另一个索引键。

答案 1 :(得分:1)

您肯定希望在数据库中使该字段唯一,然后添加javascript以进行验证,但不仅仅依赖于JS验证。在MySQL中,您可以将其作为主键或为该列添加唯一索引。如果您尝试添加相同的名称,这将引发错误,因此请确保您使用在后端(php或其他)上使用的任何技术捕获该错误,并让您的用户知道该名称已被采用。此时,您可以向服务器添加ajax调用以验证名称。