【问题标题】:Generate an error if number is repeated in a form如果数字在表单中重复,则生成错误
【发布时间】:2024-01-05 16:46:01
【问题描述】:

我有一个用于管理目的的网络表单,用户可以在其中更改一组记录在网页上的显示顺序。

例如:数据库中的一个表(tblStuff)有三个字段:

ContentID, Content, RecordPosition

该表有四条记录:

1, Guess what, 1
2, More stuff, 2
3, Some stuff, 3
4, That's right, 4

SQL代码是:

SELECT * FROM tblStuff ORDER BY RecordPosition ASC

用户可以使用表单更改 RecordPosition 编号,以便订单可以读取:

3, Some stuff, 1
2, More stuff, 2
1, Guess what, 3
4, That's right, 4

那么...我如何验证表单,以免在 RecordPosition 字段中输入两次相同的数字?

希望这是有道理的。

这是整个页面

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include virtual="/Connections/ENG.asp" -->
<%
' *** Restrict Access To Page: Grant or deny access to this page
MM_authorizedUsers=""
MM_authFailedURL="../default.asp"
MM_grantAccess=false
If Session("MM_Username") <> "" Then
  If (true Or CStr(Session("MM_UserAuthorization"))="") Or _
         (InStr(1,MM_authorizedUsers,Session("MM_UserAuthorization"))>=1) Then
    MM_grantAccess = true
  End If
End If
If Not MM_grantAccess Then
  MM_qsChar = "?"
  If (InStr(1,MM_authFailedURL,"?") >= 1) Then MM_qsChar = "&"
  MM_referrer = Request.ServerVariables("URL")
  if (Len(Request.QueryString()) > 0) Then MM_referrer = MM_referrer & "?" & Request.QueryString()
  MM_authFailedURL = MM_authFailedURL & MM_qsChar & "accessdenied=" & Server.URLEncode(MM_referrer)
  Response.Redirect(MM_authFailedURL)
End If
%>
<%
If Request.Form("action")="update" Then
  'Set variables for update
  Dim updateSQL, i
  Dim cContentID, cPositionNumber

'Loop through records on screen and update
For i = 1 To fFormat(Request.Form("counter")) 

'Create the proper field names to reference on the form
cContentID = "ContentID" & CStr(i)
cPositionNumber = "PositionNumber" & CStr(i)

'Create the update sql statement
updateSQL = "UPDATE tblContent SET PositionNumber=" & fFormat(Request.Form(cPositionNumber)) & " WHERE ContentID=" & fFormat(Request.Form(cContentID))

'Run the sql statement
Call sRunSQL(updateSQL)
Next

'Refresh page
Response.Redirect("record-order-modify-updated.asp")
End If

Function fFormat(vText)
  fFormat = Replace(vText, "'", "''")
End Function

Sub sRunSQL(vSQL)
  set cExecute = Server.CreateObject("ADODB.Command")
  With cExecute
    .ActiveConnection = MM_ENG_STRING
    .CommandText = vSQL
    .CommandType = 1
    .CommandTimeout = 0
    .Prepared = true
    .Execute()
  End With
End Sub
%>
<%
Dim rsCharityDetails
Dim rsCharityDetails_cmd
Dim rsCharityDetails_numRows

Set rsCharityDetails_cmd = Server.CreateObject ("ADODB.Command")
rsCharityDetails_cmd.ActiveConnection = MM_ENG_STRING
rsCharityDetails_cmd.CommandText = "SELECT * FROM tblCharityDetails" 
rsCharityDetails_cmd.Prepared = true

Set rsCharityDetails = rsCharityDetails_cmd.Execute
rsCharityDetails_numRows = 0
%>
<%
Dim rsNavBar
Dim rsNavBar_cmd
Dim rsNavBar_numRows

Set rsNavBar_cmd = Server.CreateObject ("ADODB.Command")
rsNavBar_cmd.ActiveConnection = MM_ENG_STRING
rsNavBar_cmd.CommandText = "SELECT * FROM tblMainMenu WHERE MainMenuID <6  OR MainMenuID >7" 
rsNavBar_cmd.Prepared = true

Set rsNavBar = rsNavBar_cmd.Execute
rsNavBar_numRows = 0
%>
<%
Dim rsContent__smID
rsContent__smID = "1"
If (Request.QueryString("smID")   <> "") Then 
  rsContent__smID = Request.QueryString("smID")  
End If
%>
<%
Dim rsContent
Dim rsContent_cmd
Dim rsContent_numRows

Set rsContent_cmd = Server.CreateObject ("ADODB.Command")
rsContent_cmd.ActiveConnection = MM_ENG_STRING
rsContent_cmd.CommandText = "SELECT tblContent.*, tblMainMenu.MainMenuName, tblSubMenu.SubMenuName, tblSubMenu.SubMenuID FROM (tblContent LEFT JOIN tblMainMenu ON tblContent.MainMenuID = tblMainMenu.MainMenuID) LEFT JOIN tblSubMenu ON tblContent.SubMenuID = tblSubMenu.SubMenuID WHERE tblContent.SubMenuID = ? AND tblContent.DisplayRecord =1 ORDER BY tblContent.PositionNumber" 
rsContent_cmd.Prepared = true
rsContent_cmd.Parameters.Append rsContent_cmd.CreateParameter("param1", 5, 1, -1, rsContent__smID) ' adDouble

Set rsContent = rsContent_cmd.Execute
rsContent_numRows = 0
%>
<%
Dim rsMenuList
Dim rsMenuList_cmd
Dim rsMenuList_numRows

Set rsMenuList_cmd = Server.CreateObject ("ADODB.Command")
rsMenuList_cmd.ActiveConnection = MM_ENG_STRING
rsMenuList_cmd.CommandText = "SELECT tblMainMenu.MainMenuID, tblMainMenu.MainMenuName, tblSubMenu.SubMenuID, tblSubMenu.SubMenuName FROM tblMainMenu INNER JOIN tblSubMenu ON tblMainMenu.MainMenuID = tblSubMenu.MainMenuID WHERE tblSubMenu.SubMenuID <> 6 AND tblSubMenu.SubMenuID <16 OR tblSubMenu.SubMenuID >19" 
rsMenuList_cmd.Prepared = true

Set rsMenuList = rsMenuList_cmd.Execute
rsMenuList_numRows = 0
%>
<%
Dim rsHeaderImage
Dim rsHeaderImage_cmd
Dim rsHeaderImage_numRows

Set rsHeaderImage_cmd = Server.CreateObject ("ADODB.Command")
rsHeaderImage_cmd.ActiveConnection = MM_ENG_STRING
rsHeaderImage_cmd.CommandText = "SELECT MainMenuImage, MainMenuID FROM tblMainMenu" 
rsHeaderImage_cmd.Prepared = true

Set rsHeaderImage = rsHeaderImage_cmd.Execute
rsHeaderImage_numRows = 0
%>
<%
Dim navBar__numRows
Dim navBar__index

navBar__numRows = -1
navBar__index = 0
rsNavBar_numRows = rsNavBar_numRows + navBar__numRows
%>
<%
Dim rptContent__numRows
Dim rptContent__index

rptContent__numRows = -1
rptContent__index = 0
rsContent_numRows = rsContent_numRows + rptContent__numRows
%>
<%
Dim Repeat_MenuList__numRows
Dim Repeat_MenuList__index

Repeat_MenuList__numRows = -1
Repeat_MenuList__index = 0
rsMenuList_numRows = rsMenuList_numRows + Repeat_MenuList__numRows
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="iso-8859-1">

<!-- disable iPhone inital scale -->
<meta name="viewport" content="width=device-width; initial-scale=1.0">

<title><%=(rsCharityDetails.Fields.Item("CharityName").Value)%> | English Website Administration</title>
<!-- main css -->
<link href="../../scripts/mfm-standard-stylesheet.css" rel="stylesheet" type="text/css">

<!--[if lt IE 9]>
<link href="../scripts/mfm-standard-stylesheet_ie.css" rel="stylesheet" type="text/css">
<![endif]-->

<!-- Admin css -->
<link href="../scripts/mfm-admin-stylesheet.css" rel="stylesheet" type="text/css">

<script src="../../scripts/jquery-1.7.2.min.js"></script>
<!-- jQuery NailThumb Plugin - any image to any thumbnail Examples and documentation at: http://www.garralab.com/nailthumb.php -->
<script src="../../scripts/jquery.nailthumb.1.1.js"></script>
<!-- Lightbox2 v2.51 by Lokesh Dhakar For more information, visit: http://lokeshdhakar.com/projects/lightbox2/ -->
<script src="../../scripts/lightbox.js"></script>
<!-- Lightbox css -->
<link href="../../scripts/lightbox.css" rel="stylesheet" type="text/css" media="screen" />
<script src="../tiny_mce/tiny_mce.js"></script>
<script src="../tiny_mce/tiny-mce-mfm.js"></script>

<!-- html5.js for IE less than 9 -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

<!-- css3-mediaqueries.js for IE less than 9 -->
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->

</head>

<body id="other">

<div id="wrapper">
<header class="innerWidth">
<!--#include file="includes/header-modify-record.asp" -->
</header>

<nav class="innerWidth">
<!--#include file="includes/navbar-modify-record.asp" -->
</nav>

<!-- pageContent -->
<div id="content" class="innerWidth">

<!-- Aside -->
<aside>

<h3>Record Order</h3>

<ul>
<% 
Dim txtOldHeading
txtOldHeading = ""
    While ((Repeat_MenuList__numRows <> 0) AND (NOT rsMenuList.EOF)) 
If txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value Then
Else
txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value
%>
<li class="menuHeading"><%=(rsMenuList.Fields.Item("MainMenuName").Value)%></li>
<%
END IF
%>
 <li class="menuList">
 <% If (rsMenuList.Fields.Item("SubMenuID").Value) = "3" Then %>
     <a href="our-development-partners-record-order-modify.asp"><%=(rsMenuList.Fields.Item("SubMenuName").Value)%></a>
 <% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "15" Then %>
     <a href="shop-record-order-modify.asp"><%=(rsMenuList.Fields.Item("SubMenuName").Value)%></a>
 <% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "20" Then %>
     <a href="friends-of-mfm-record-order-modify.asp"><%=(rsMenuList.Fields.Item("SubMenuName").Value)%></a>
 <% Else %>
     <a href="record-order-modify.asp?smID=<%=(rsMenuList.Fields.Item("SubMenuID").Value)%>"><%=(rsMenuList.Fields.Item("SubMenuName").Value)%></a>
     <% End If %>
 </li>
 <% 
 Repeat_MenuList__index=Repeat_MenuList__index+1
 Repeat_MenuList__numRows=Repeat_MenuList__numRows-1
 rsMenuList.MoveNext()
Wend
%>
</ul>
</aside>
<!-- /Aside -->

<!-- Article -->
<article>
<% IF Request.ServerVariables("QUERY_STRING") <> "" THEN %>
<h3><span style="font-size:small">Order/Re-order records for: </span><%=(rsContent.Fields.Item("SubMenuName").Value)%></h3>
<% 
Dim counter
While ((rptContent__numRows <> 0) AND (NOT rsContent.EOF)) 
counter = counter + 1
%>
<form action="record-order-modify.asp" method="post" class="recordPosition">
  <table width="100%">
    <tr>
      <td align="left" valign="top" name="ContentTitle" colspan="2"><h2><%=(rsContent.Fields.Item("ContentTitle").Value)%></h2><input type="hidden" value="<%=(rsContent.Fields.Item("ContentID").Value)%>" name="ContentID<%=counter%>"></td>
      </tr>
    <tr>
      <td align="left" valign="top" name="ContentData"><%
    Dim tmp
    tmp = rsContent.Fields.Item("ContentData").Value
    %>
        <% =LEFT(tmp, INSTR((tmp & "."), ".")) %>..
       </td>
      <% IF (IsNull(rsContent.Fields.Item("ContentImage").Value)) THEN %>
      <td width="140" align="center" valign="top" name="ContentImage"><img src="../images/system_images/red-x.png"></td>
      <% ELSE %>
      <td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
        <!-- Thumbnail Container -->
        <img src="<%=(rsContent.Fields.Item("ContentImage").Value)%>"> </div></td>
      <% END IF %>
      </tr>
    <tr>
      <td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label>&nbsp;&nbsp;<input type="text" name="PositionNumber<%=counter%>" tabindex="<%=counter%>" value="<%=(rsContent.Fields.Item("PositionNumber").Value)%>"></td>
      </tr>
  </table>
  <hr>
  <% 
  rptContent__index=rptContent__index+1
  rptContent__numRows=rptContent__numRows-1
  rsContent.MoveNext()
Wend
%>
<table align="center" class="positionButtons">
<tr>
<td width="50%" align="right"><input name="Submit" type="submit" value="Update Positions" tabindex="<%=counter%>"></td>
<td width="50%" align="left"><input name="Reset" type="reset" value="Reset All Changes" tabindex="<%=counter%>"></td>
</tr>
</table>
<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="<%=counter%>">
</form>
<% ELSE %>
<h3>Select a listing to order/re-order using the list on the left.</h3>
<% END IF %>
</article>
<!-- /Article -->

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('.nailthumb-container').nailthumb({width:125,height:125,fitDirection:'top center'});
    });
</script>

</div>
<!-- /pageContent -->

<div class="push"></div>
</div>
<!-- #wrapper -->

<footer class="innerWidth">
<!--#include file="includes/footer.asp" -->
</footer>

</body>
</html>
<%
rsCharityDetails.Close()
Set rsCharityDetails = Nothing
%>
<%
rsNavBar.Close()
Set rsNavBar = Nothing
%>
<%
rsContent.Close()
Set rsContent = Nothing
%>
<%
rsMenuList.Close()
Set rsMenuList = Nothing
%>
<%
rsHeaderImage.Close()
Set rsHeaderImage = Nothing
%>

应阿连德的要求,这是生成的表单代码。

<form action="record-order-modify.asp" method="post" class="recordPosition">

  <table width="100%">
    <tr>
      <td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Investing in people and the environment</h2><input type="hidden" value="15" name="ContentID1"></td>
      </tr>
    <tr>
      <td align="left" valign="top" name="ContentData"><p>Madagascar is an environmental hotspot...
       </td>

      <td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
        <!-- Thumbnail Container -->
        <img src="/images/framed-images/mfm-website-(26).jpg"> </div></td>

      </tr>
    <tr>
      <td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label>&nbsp;&nbsp;<input type="text" name="PositionNumber1" tabindex="1" value="1"></td>
      </tr>
  </table>
  <hr>

  <table width="100%">
    <tr>
      <td align="left" valign="top" name="ContentTitle" colspan="2"><h2>The next generation</h2><input type="hidden" value="16" name="ContentID2"></td>
      </tr>
    <tr>
      <td align="left" valign="top" name="ContentData"><p>Teaching Malagasy children to respect and nurture their environment is critical to the survival of Madagascar's biodiversity...
       </td>

      <td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
        <!-- Thumbnail Container -->
        <img src="/images/framed-images/mfm-website-(292).jpg"> </div></td>

      </tr>
    <tr>
      <td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label>&nbsp;&nbsp;<input type="text" name="PositionNumber2" tabindex="2" value="2"></td>
      </tr>
  </table>
  <hr>

  <table width="100%">
    <tr>
      <td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Recognition for our work</h2><input type="hidden" value="17" name="ContentID3"></td>
      </tr>
    <tr>
      <td align="left" valign="top" name="ContentData"><p>Our work over 2 decades with 73 villages surrounding the Reserve of Betampona recently gained recognition at an international conference held at the University of East Anglia...
       </td>

      <td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
        <!-- Thumbnail Container -->
        <img src="/images/framed-images/mfm-website-(56).jpg"> </div></td>

      </tr>
    <tr>
      <td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label>&nbsp;&nbsp;<input type="text" name="PositionNumber3" tabindex="3" value="3"></td>
      </tr>
  </table>
  <hr>

  <table width="100%">
    <tr>
      <td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Adding value by adding forests</h2><input type="hidden" value="18" name="ContentID4"></td>
      </tr>
    <tr>
      <td align="left" valign="top" name="ContentData"><p>Often the best way to protect an old forest is to plant a new one...
       </td>

      <td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
        <!-- Thumbnail Container -->
        <img src="/images/framed-images/mfm-website-(217).jpg"> </div></td>

      </tr>
    <tr>
      <td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label>&nbsp;&nbsp;<input type="text" name="PositionNumber4" tabindex="4" value="4"></td>
      </tr>
  </table>
  <hr>

<table align="center" class="positionButtons">
<tr>
<td width="50%" align="right"><input name="Submit" type="submit" value="Update Positions" tabindex="4"></td>
<td width="50%" align="left"><input name="Reset" type="reset" value="Reset All Changes" tabindex="4"></td>
</tr>
</table>
<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="4">
</form>

【问题讨论】:

  • 您的问题是如何进行验证是 ASP 还是如何防止 MySQL 端的重复值?
  • 你需要查看 MySQL 的主键和自动增量
  • 这并不是关于不允许表格中的重复。这些表已经对主键使用自动增量。
  • 你能发布生成的 HTML,(只是带有记录的表单代码)吗?

标签: javascript jquery mysql sql asp-classic


【解决方案1】:

如果您想防止 RecordPosition 中的重复值,无论您如何插入/更新它们,您都可以在此列中创建唯一约束

CREATE UNIQUE INDEX uq_idx_RecordPosition ON tblStuff(RecordPosition);

这里是SQLFiddle演示

【讨论】:

  • 允许重复。我只是用这个例子来尽量保持简单。对不起。我已经为页面添加了整个代码。
【解决方案2】:

如果您尝试进行一些客户端验证,则必须构建一个包含所有 RecordPosition 值的数组。

一旦你有了它,你可以检查数组是否有重复。这已在 SO 上被问过几次:Easiest way to find duplicate values in a JavaScript array

很遗憾,我无法提供更多帮助,因为您没有包含任何显示网页结构的代码

【讨论】:

  • 我已经添加了整个页面,这样您就可以看到我正在处理的内容。感谢您的链接。
【解决方案3】:

在将数据插入数据库之前检查

ex: 记录位置值 3 --> 1 然后传递值 1

SELECT * FROM tblStuff where RecordPosition=1

如果记录存在,则向用户发送消息,该位置存在

【讨论】:

    【解决方案4】:

    假设你有这样的表格(注意所有的输入都有相同的类):

    <form id="myForm" method="POST" action"someUrl">
        <input type="text" class="recordPosition"></input>
        <input type="text" class="recordPosition"></input>
        <input type="text" class="recordPosition"></input>
        <input type="text" class="recordPosition"></input>
    </form>
    

    你可以用 jQuery 做这样的事情:

     $(document).ready(function(){
    
     $(".recordPosition").on("blur", function(){
         var allFieldsForOrder = $('.recordPosition');
         var count = 0;
         var i=0
        //console.log(allFieldsForOrder.length );
          while((i<allFieldsForOrder.length) && (count < 2)){
                 if ($(allFieldsForOrder[i]).val()===$(this).val())
                {
                 count++                 
                }
                i++;
         } 
    
         if (count==2){
            alert("A duplicated value"); return false;}
        }); 
     });
    

    对于您发布的 html,您可以使用: 注意我不存储重复值的位置。

    $(document).ready(function(){
        //console.log($("input[type='text'][name^='PositionNumber'").length);
        $("input[type='text'][name^='PositionNumber'").each(function(){
             $(this).on("blur", function(){
    
             var allFieldsForOrder = $("input[type='text'][name^='PositionNumber'");
             var count = 0;
             var i=0
    
             while((i<allFieldsForOrder.length) && (count < 2)){
                    if ($(allFieldsForOrder[i]).val()===$(this).val())
                    {
                     count++                 
                    }
                    i++;
             }
    
             if (count==2){
                alert("A duplicated value"); 
             }
    
           });
        });
      });
    

    对于上面的代码,我们假设您要检查属性名称以字符串“PositionNumber”开头的所有字段

    稍后我会尝试减少代码,我认为有一种最短的方法可以检查是否重复了“RecordPosition”值,但需要测试一些想法。

    这将是您的解决方案(其中之一):

      $(document).ready(function(){
    
    
        $('form').on("submit",function(){
                var tempArray=[];
                $("input[type='text'][name^='PositionNumber'").each(function(){
                    tempArray.push($(this).val());
                });
    
                var i=0;
                var duplicated=false;
                var currentElement;
                while((tempArray.length >= 0) && (duplicated==false)){                  
                    //pop it out from the array
                   currentElement = tempArray.pop();
                   duplicated = tempArray.indexOf(currentElement)          
    
                }
    
                //after you can use "duplicated" to cancel the submit
                if (duplicated){                    
                    alert("duplicated value:" + currentElement);
                    return false;
                }
    
        });
      });
    

    我更短的版本:

    $(document).ready(function(){           
     $('form').on("submit",function(){
             var tempArray=[];            
            var exists=0;
             $("input[type='text'][name^='PositionNumber'").each(function(){
                 exists = tempArray.indexOf($(this).val());             
                 if (exists>=0){                    
                     return false;//break the loop
                 }
                 tempArray.push($(this).val());                  
             });
    
             //after you can use "exist" to check if duplicated and retrieve the value to cancel the submit
             if (exists>=0){                   
                 alert("duplicated value:" + tempArray[exists]);                
             } else{
                 alert("no duplicated value:");
             }
    
            return false;            
     }); 
    });
    

    【讨论】:

    • 耶!上面的代码可以改进(我很确定,即使我不知道如何),我有一个检查重复值的最短方法的想法,因为我在工作没有时间测试它待会儿见!
    • 干杯 A. 我正在玩游戏,看看是否可以添加已重复的数字。
    • 在警报中做alert("A duplicated value: " + $(allFieldsForOrder[i-1]).val());
    • 感谢您对脚本的更改。从表单中使用输入标签而不是类事件的更改非常好。我期待看到其他想法。另外,感谢更改脚本。我说对了一部分。我没有使用 $ 并将 i-1 括在方括号中(我使用了圆括号)。
    • 顺便说一句,有没有办法在点击提交按钮时检查重复项?