Required field validator not working - asp.net

I have used a required field validator followed by a regular expression validator but the required field validator is not working.....
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
ValidationGroup="Valtxt" TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" Display="Dynamic"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
Invalid characters(<>&#!) are not allowed
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required"
ValidationGroup="Valtxt" Display="Dynamic">
</asp:RequiredFieldValidator>
can anyone sees the problem???

The RequiredFieldValidator is triggered by the client side onchange event. It sounds like you're expecting it to be triggered by the onblur event, such that tabbing away from the textbox would fire the validation.
Before jumping to that, I suspect this is what you are seeing and to validate that it's actually working you need to trigger onchange. To do so, enter some text in the textbox, tab away, tab back to it, clear the textbox, then tab away once more. You should now see the RequiredFieldValidator's error message since it's contents have changed.
Back to the onblur issue. To accomplish that behavior you could add the onblur attribute in your code-behind and have it call the ValidatorValidate(...) JavaScript method as follows:
void Page_Load(object sender, EventArgs e)
{
txtSummary.Attributes.Add("onblur", "ValidatorValidate(" + reqvalSummary.ClientID + ")");
}
Alternately, you could accomplish the same thing in markup. First, add this script block:
<script type="text/javascript">
function rfvBlur() {
var rfv = document.getElementById("<%= reqvalSummary.ClientID %>");
ValidatorValidate(rfv);
}
</script>
Second, update the <asp:TextBox.../> markup by adding onblur="rfvBlur()" so that it now looks like this:
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px" CausesValidation="true"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000" ValidationGroup="Valtxt"
TabIndex="2" Rows="4" onblur="rfvBlur()" />
Yet another option is to validate the entire ValidationGroup by adding the following attribute to your <asp:TextBox.../> markup (no additional script block needed):
onblur="Page_ClientValidate('Valtxt')"

Adding this line to <appSettings> section of web.config worked for me (I had a problem when all validators stopped working when project was upgraded to .NET 4.5):
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Source:
http://forums.asp.net/t/1876231.aspx?ASP+Net+4+5+Validation+Controls+not+working+with+AJAX+ToolkitScriptManager1

Why don't you change the regular expression of the "RegEx" validator to check if the textbox is empty instead of use another validator?
Anyway probabily you have not specify ValidationGroup="Valtxt" for the button or the control that raise the postback. Just add ValidationGroup="Valtxt" to the button or the server control that raise the post to the page

I put the following at the top of my btn_Click event handler (to prevent further code execution) and upon 'return', the rfv messages show...
Page.Validate("your validation group");
if (!Page.IsValid)
{
return;
}

<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Invalid characters(<>&#!) are not allowed" Text="*"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required" Text="*"
ValidationGroup="Valtxt">
</asp:RequiredFieldValidator>

Related

ASP.NET Required Field Validator not working

Hi all I need a required field validator for my textbox..This is my textbox..
<asp:TextBox ID="txtTimeSlotGroupName" runat="server" AutoPostBack="false"
ClientIDMode="Static"></asp:TextBox>
<font color="red">*</font>
<asp:RequiredFieldValidator ID="RequiredFieldValidator_txtTimeSlotGroupName"
runat="server" ControlToValidate="txtTimeSlotGroupName" Display="None"
ErrorMessage="Timeslot Group Required!" ForeColor="Red" InitialValue="0"
ValidationGroup="TimeSlot"></asp:RequiredFieldValidator>
My button:
<asp:Button ID="btnAddTimeSlots" Text="Add Timeslots" CssClass="button"
runat="server" OnClick="btnAddTimeslots_Click" ValidationGroup="TimeSlot"
OnClientClick="javascript:shouldsubmit=true;"/>
I am not getting the error message. Any solutions?
You have to define the Validation Group Of your Textbox too....to make it work
<asp:TextBox ID="txtTimeSlotGroupName" runat="server"
AutoPostBack="false" ValidationGroup="TimeSlot" ClientIDMode="Static"></asp:TextBox>
Remove InitialValue="0" from the RequiredFieldValidator tag, it is not required when you are validating the textbox.
Even I was facing the same issue. Kindly check if any javascript are present on your page. Irrespective of above make use of Page.Validate() method and if(Page.IsValid) in your code. This will automatically force your validation controls and issue will be solved
If two objects have the same id the required field validator Does not work.
You just add ValidationGroup="TimeSlot" in textbox
<asp:TextBox ID="txtTimeSlotGroupName" runat="server" AutoPostBack="false"
ValidationGroup="TimeSlot" ClientIDMode="Static"></asp:TextBox>
I had this same issue... but none of the above answers were the fix for me...
My problem was that I was missing the Page.isValid in my button press method. Below is my button code and the method called by the button.
Button:
<asp:Button ID="btnBtmSave" runat="server" Text="Save" OnClick="btnSave_Click" BtnGroup="save" TabIndex="18" />
Button method:
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Logic goes here
}
}
make the same Validation Group Of all your text and Add button and Validation
ValidationGroup="AAA"
and add the code to your save button:
If (Page.IsValid) Then
YOURSQL.Insert()
'or ur code here'
End If
In my case, For button, I was using both client side validation i.e onClientClick="return validate()", and ASP.NET Validation i.e Reguired field Validation (ValidationGroup). Hence the Required field validators were not firing.

input button causes RequiredFieldValidator to fire

I have an input button on my page that is dynamically created, every time I press it, it fires the RequiredFieldValidator for the blank field in the email address.
is there a way to ovverride it?
input code:
<input class=\"hledat\" id=\"searchbutton\" type=\"image\" src=\"search-button.gif\" value=\"{0}\" onclick=\"search('{1}');\" onkeypress=\"search('{1}');\"/>"
validator code:
<asp:TextBox runat="server" ID="txtEmail" ClientIDMode="Static" Width="98%" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" ErrorMessage="email"
Display="dynamic" ValidationGroup="newsletter" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtEmail" ErrorMessage="email"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="dynamic"
ValidationGroup="newsletter" />
I have an input button on my page that is dynamically created, every
time I press it, it fires the RequiredFieldValidator for the blank
field in the email address. is there a way to ovverride it?
HtmlButton.CausesValidation Property
Mark UP
<button causesvalidation="false" /><button ID="StateQueryButton"
CausesValidation="False"
runat="server">
Submit
</button>
yes, i want it to do a postback
HtmlButton.OnServerClick Method
Code Behind
protected void FancyBtn_Click(object sender, EventArgs e)
{
}
Mark Up
<button causesvalidation="false" /><button ID="StateQueryButton"
CausesValidation="False"
OnServerClick=" FancyBtn_Click"
runat="server" >
Submit
</button>
Make it server side button by writing runat="Server" attribute and make a CausesValidation="true|false" on your requirements. If you do false it will not validate. Do let me know if it solves the problem
try to add runat="server" to input button as shown:
*Note* the runat="server". While asp:button probably renders similarly, if what you really want it an HTML button input, you can use that. Yes, ASP.NET will pick up the value on the server side.**
<input type="button" runat="server" id="btnTest" value="change" onclick="doPostBack('btnTest', '');"/>

force user select from autocomplete

i am beginner for asp.net . I now facing a problem . How can i force a user to select option from ajax control toolkit autocomplete?
Here is my sample code
<cus:cusTextBox ID="txtCMemberID" runat="server" Action="Edit"
CssClass="inputTextM" OnTextChanged="txtCMemberID_TextChanged"
AutoPostBack="True"></cus:cusTextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
ServicePath="~/Module/Common/autoComplete/acLewreMember.asmx"
MinimumPrefixLength="1" ServiceMethod="GetSuggestedStrings"
TargetControlID="txtCMemberID" CompletionInterval="10"
CompletionSetCount="3" EnableCaching="true"
CompletionListCssClass="completionListElement"
CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="highlightedListItem"
FirstRowSelected="True"
ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>
As you see the textbox is a custom control. Is that any way to force user to select option from autocomplete?Please provide me a sample code also. thanks
ASP.NET includes a useful feature called a validator.
<asp:TextBox ID="TextBox2" ValidationGroup="Group2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ErrorMessage="*Required" ValidationGroup="Group2"
ControlToValidate="TextBox2" runat="server" />
<asp:Button ID="Button2" Text="Validate Group2"
ValidationGroup="Group2" runat="server" />
Here is the resource link for msdn: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
I'm not sure how these work with custom controls as I'm relatively new at asp. They also have a custom validator which might be more suited for your purposes, but like I said. I don't know exactly.
Note: If the client is using an old browser this won't work, so you also want to check on the server that this field isn't empty by using:
if (Page.IsValid)
{
//stuff to do in your event handler
}

asp.net required field validation called on every button action

I wrote a simple asp.net code with the asp.net required validator control, the problem is that I only have one submit button called GO, and a dropdownlist that looks for the selection :
clear, submit, cancel.
No matter what option is selected, the required field validation is being fired.
Is there a way to code the page so only when the selected value is Submit it validates?
<asp:TextBox runat="server" id="txtName" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
<br /><br />
<asp:DropDownList ID="dpAction" runat="server">
<asp:ListItem>Submit</asp:ListItem>
<asp:ListItem Value="Reset">Reset</asp:ListItem>
<asp:ListItem>Cancel</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnAction" runat="server" onclick="btnAction_Click" Text="Go"
Width="40px" />
You will probably have to use a custom validator, and you would need to write the client side code for it also if you want client side validation.
I'm assuming you have a text box or something else that is required when "dpAction" is set to "Submit"?
So for example you would do something like this in your markup
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
ControlToValidate="TextBox1"
ErrorMessage="Text must be specified if Submit is selected">
and in your code-behind
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = dpAction.SelectedValue == "Submit" && !String.IsNullOrEmpty(textbox1.Text);
}
using "required" attribute.
its new in html 5
you should set ValidationGroup for each Validator!
for all controls that you want to be validated and the button to fire the validation:
and the button must have same validaton group with your validator!

AutoPostBack on CheckBox control sometimes fails

If have the below markup.
<asp:checkbox id="chkTVLic" runat="server" text="TV Licence" oncheckedchanged="chkDocs_CheckChanged"
autopostback="true" CausesValidation="false" />
<asp:panel id="pnlTVLic" runat="server" visible="false">
<div class="toggle-item-link1 document-date">
<asp:panel id="pnlTVLicIssueDate" runat="server">
<p>
Please enter the date of issue
</p>
<div class="fm-req">
<asp:textbox id="txtTVLicIssueDate" cssclass="tb size2" runat="server" onblur="return true;"></asp:textbox>
<cc2:calendarextender id="caleTVLicIssueDate" runat="server" targetcontrolid="txtTVLicIssueDate"
popupbuttonid="ibnTVLicIssueDate" popupposition="BottomLeft" animated="true"
format="dd/MM/yyyy">
</cc2:calendarextender>
<asp:imagebutton id="ibnTVLicIssueDate" runat="server" imageurl="../images/img-calendar-day.png"
alternatetext="Calendar" tooltip="Pick Date" cssclass="date-picker" />
<asp:requiredfieldvalidator id="rfvTVLicIssueDate" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
display="Dynamic" errormessage="Required" setfocusonerror="true" validationgroup="TVLic"></asp:requiredfieldvalidator>
<asp:comparevalidator id="cmvTVLicIssueDate" CssClass="error" runat="server" errormessage="Not a valid date"
controltovalidate="txtTVLicIssueDate" operator="DataTypeCheck" type="Date" setfocusonerror="true"
validationgroup="TVLic" display="Dynamic" cultureinvariantvalues="true"></asp:comparevalidator>
<asp:customvalidator id="cuvTVLicIssueDate12Months" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
validationgroup="TVLic" display="Dynamic" onservervalidate="cuvDocIssueDate12Months_ServerValidate"
errormessage="Document must be less than 12 months old."></asp:customvalidator>
</div>
</asp:panel>
<asp:panel id="pnlTVLicApprove" runat="server">
<asp:LinkButton id="lbnTVLicApprove" runat="server" CssClass="screen-hide"
alternatetext="Confirm TV Licence" tooltip="Confirm TV Licence" Text="OK" CausesValidation="false" OnClick="lbnApproveConfirm_Click" />
<asp:imagebutton id="ibnTVLicApprove" runat="server" imageurl="../images/img-accept-doc-off.png"
alternatetext="Approve" tooltip="Approve" cssclass="approval-btn" causesvalidation="true" validationgroup="TVLic" OnMouseDown="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" OnClientClick="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" />
<span class="approval-label">Accept document:</span></asp:panel>
</div>
</asp:panel>
The app is written in c# but i havn't posted any actual code as all the user code related to this markup seems to work fine.
The problem is the CheckBox chkTVLic has causes validation set to false and autopostback set to true. So whatever happens when i check and uncheck the checkbox it should postback. Most of the time this is exactly what it does and the result is to show and hide pnlTVLic when it is checked and unchecked. However if any on the validators within the panel fire, the checkbox does not cause a postback the first time. It will on all subsequent times but never the first. However it should ALWAYS cause a postback. What could be stopping it. Before someone asks there is no use written client side code, everything is pure .net markup and c# code.
I don't see why it shouldn't postback when you check/uncheck the checkbox, but if the only purpose of that checkbox is to hide/unhide a panel, I would rather do it in javascript. Doing a full postback to the server just for hiding some panel seems really bad.
In javascript you can do this to hide the panel:
document.getElementById('<%=pnlTVLic.ClientID%>').display='none';
And this to show it:
document.getElementById('<%=pnlTVLic.ClientID%>').display='block';
It's going to be so much faster and better. Just put a regular checkbox instead of the ASP.NET one and subscribe to the onclick event.
Sorry, one more comment:
I think you are wrong when you say that the checkbox should ALWAYS cause a postback. No, if one of the validators fires inside the panel, the checkbox will not cause a postback until the condition is satisfied.
This is what I did and it worked.
on checkbox onclick event I disabled all the validation controls and immediately did Page_ClientValidate(); and it worked.

Resources