I have a non standard submit button in my ASP.NET form along the lines of.
<a class="button" href="#" onclick="this.blur();SubmitForm();"><span>Submit</span></a>
Due to this, my required field validator is not being invoked on the client side. How can the required field validator be invoked through Javascript?
Alternatively is there a better way to accomplish what I am attempting to do?
You can use in built client side function named Page_ClientValidate
for this.Check out the following code snippet for the reference
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientSide_Validation.aspx.cs"
Inherits="ClientSide_Validation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function performCheck() {
if (Page_ClientValidate()) {
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lbl1" runat="server" Text="Please enter some value"></asp:Label>
<asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valReq" ControlToValidate="txtbox1" runat="server"
ErrorMessage="*" Display="Dynamic">
</asp:RequiredFieldValidator>
<input type="button" id="btnValidate" value="Submit" onclick="performCheck()" />
<a href="#" onclick="performCheck();">Validate</a>
</div>
</form>
</body>
</html>
Page_ClientValidate
triggers validation for all validators on the form and as @gilly3 shows out you can also validate them all by looping the collection and calling ValidatorValidate(validator)
However if you want to validate just one particular validator then you need to call ValidatorValidate(validator)
for just one item.
The validator argument needs to be a DOM object which can be tricky to get because the element ID might end up quite different than you specified in the mark up if you are using master pages or user controls.
e.g.
<asp:RequiredFieldValidator ID="rfvCampaignStartDate" runat="server" .../>
becomes
<span id="cph_0_rfvCampaignFile" ...>
I got around this in one of my projects by using a jQuery selector like this
ValidatorValidate($('[id$="rfvCampaignFile"]').get(0));
ASP.NET only prefixes the IDs to create a unique name I could use id$=
part of the selector to match any IDs ending in "rfvCampaignFile"
since I wrote the website I know it won't clash with other controls. Finally I use .get(0)
to return the DOM object reference to the first (and only in my case) DOM object matched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With