问题
I implemented a Custom Validator with AJAX, and It works fine:
EDITED. Add ASPX code
<asp:DetailsView ID="DetailsView" runat="server" Height="50px" Width="25em" DataSourceID="SqlDataSource1" AutoGenerateRows="False" DefaultMode="Insert" CellPadding="4" ForeColor="#333333" GridLines="None" OnItemInserting="DetailsView_ItemInserting">
<Fields>
<asp:TemplateField HeaderText="Nombre *">
<InsertItemTemplate>
<asp:TextBox ID="txtNombre" runat="server" Text='<%# Bind("nombre) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="requireNombre" runat="server" ControlToValidate="txtNombre" ErrorMessage="El campo 'Nombre' no puede estar vacío." ValidationGroup="DetailsGroup" Display="None"></asp:RequiredFieldValidator>
<asp:CustomValidator id="CustomValidator1" ControlToValidate="txtNombre" ClientValidationFunction="validateNombre" ValidationGroup="DetailsGroup" Display="none" ErrorMessage="Introduzca un nombre diferente." runat="server"/>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Function AJAX:
function validateNombre(src, args) {
var isValid;
$.ajax({
type: "POST",
url: "Nombre.aspx/ComprobarNombre",
data: "{'nombre': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
isValid = msg.d;
}
});
args.IsValid = isValid;
ComprobarNombre: [WebMethod()]
public static bool ComprobarNombre(string nombre)
{
/* SQLConnections... */
if(...)
return false;
else
return true;
}
The problem is that the AJAX function is launched when every time I enter a value in the TextBox. I need that the function launch only when I click the button of the form.
回答1:
1) Eliminate Custom validator 2) On button click call client side function validateNombre() 3) Fetch the textbox data inside the function 4) and pass it in as data parameter
来源:https://stackoverflow.com/questions/17162742/asp-net-custom-validator-and-ajax