Set the order of asp.net validator - asp.net

I'm using 3 validators to validate the TextBox, but all get triggered when invalid value is entered in the Textbox. But I want to these validators to work in a particular order so that users can resolve these faults one by one.
<asp:TextBox ID="txt_temp" runat="server"></asp:TextBox>
<asp:CompareValidator ID="cv_txt_temp" runat="server" CssClass="error" ControlToValidate="txt_temp" ValueToCompare="0" Type="Double" Operator="GreaterThanEqual" ValidationGroup="insert" SetFocusOnError="true" ErrorMessage="Must be valid value" Display="Dynamic"></asp:CompareValidator>
<asp:RegularExpressionValidator ID="rev_txt_temp" CssClass="error" SetFocusOnError="true"
runat="server" ErrorMessage="Value upto 1 decimal place" Display="Dynamic" ControlToValidate="txt_temp" ValidationExpression="\d+(?:(?:\.|,)\d{0,1})?" ValidationGroup="insert"></asp:RegularExpressionValidator>
<asp:RangeValidator ID="rv_txt_temp" Display="Dynamic" runat="server" SetFocusOnError="true" ValidationGroup="insert" ControlToValidate="txt_temp" Type="Double" CssClass="error"></asp:RangeValidator>

The validators that you add automatically add themselves to Page.Validators collection in the order they are created. The validation runs thorugh in the order they are present in the Page.Validators collection which means the first validator definition shown in the aspx file is first in Page.Validators. If you want to change the order, then the only way is to get all of your validators into the page in the order you want them to fire.
Edit : In your case the only way is to use css to overlap the validators.

You can use Custom Validator, Custom Java Script or Mask edit validator

You can try with only RegularExpressionValidator
<asp:RegularExpressionValidator ID="rev_txt_temp" CssClass="error" SetFocusOnError="true"
runat="server" ErrorMessage="Error.." Display="Dynamic" ControlToValidate="txt_temp"
ValidationExpression="^[1-9]\d*(\.\d{0,1})?$" ValidationGroup="insert">
</asp:RegularExpressionValidator>
let me know, if you want in other way..

My solution of "setting validation order" is:
On Page where have validators:
1) I set AutoEventWireup to false in aspx code and use custom validators
2) I create and call functions for validations and sett "IsValid" for related validators:
validCustom1.IsValid = Validation1(textbox1.Text);
if (Page.IsValid)
validCustom2.IsValid = Validation2(textbox2.Text);
if (Page.IsValid)
validCustom3.IsValid = Validation3(textbox3.Text);
if (Page.IsValid)
{
//Do somethink
}
else
{
//Do somethink else
}

You can create your custom Validation. It will takes time, but you can control order of validation.
You can also use masked textbox extender.

Related

Multiple validation groups, only validate one on control blur

Summary
I have a single control with two (almost) identical validators, each linked to two validation groups. When the cursor leaves the control, both validators are automatically checked by ASP.NET. Is there a way to only fire one (without setting EnableClientScript="false") so there are not two * symbols being displayed on the blur?
Details
I have a form with two buttons asp:btnSave and asp:btnSubmit... both buttons require validation, as certain controls must be validated on the save for it to work correctly.
So I have two validation groups, the "default" group for submitting (i.e. ValidationGroup property is NOT set), and the "SaveGroup" for saving. There are two asp:ValidationSummary controls to reflect these.
On a single control that is (for example) designed to accept a decimal value, I have the following. Firstly a required field for the submit, then a range validator for the submit. Then a 3rd validator which is a replication of the range validator but is part of the "SaveGroup"...
<asp:TextBox runat="server" id="txtMyDecVal" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" />
This is working fine, and the two buttons validate correctly.
The problem is... there is a visual issue that if you type invalid text into the control, BOTH the RangeValidators are fired automatically by ASP.NET when the cursor leaves the control, resulting in two * symbols appearing.
Is there a way to make it so that only one of those validators are checked as part of the blur event on the control?
I could set EnableClientScript="false" on one of the validators, but I still want it to check the control on the client side without a post-back first.
Update
I have been playing with setting EnableClientScript="false" as I decided that the post-back on the save wasn't actually going to be a big issue.
However, this then leads on to another visual issue: Enter invalid text, the "submit" validator shows the *. Click the save, which posts-back and then displays the * for the "save" validator. If you then change the text to valid text, the "save" validator doesn't disappear, so it still looks like there's a problem... and if you change the text to different invalid text, you get the "submit" * appearing as well, resulting in the same as before... i.e. two * symbols.
You should add Display="Dynamic" to your validators.
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" Display="Dynamic"/>
Courtesy of Satheesh babu's artice, and having toyed with a couple of options -- I think the best way to deal with complex situations is to DIY.
I've set CausesValidation="False" and removed ValidationGroups from buttons, and put something like:
OnClientClick="if (EnableVal(['ValidationGroup1','ValidationGroup2']) == false) {return false;}"
for client-side validations, where particular buttons validate increasingly complex rules as the process moves ahead. This allows me to reduce duplicating validators.
Then, on server-side, I am calling Page.Validate("ValidationGroup#") for each group, depending on the buttons or even business process state, and then finally checking Page.IsValid.
Also, depending on the business process state, the buttons' OnClientClicks can be set from code-behind depending on which validation groups I want to deal with right now.
Finally, to combine validation summaries, see the javascript here: Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously? (with some tweaks).
Net very elegant, but probably gives the most control.
I am faced with this issue too - I have:
Multiple ValidationGroups triggered by different buttons
Validations that need to take place in both groups (in my case RequiredFieldValidators)
Adding multiple validators works as above until you enter and then subsequently blank out a field - you get both messages. My workaround is as follows:
Overwrite the IsValidationGroupMatch JavaScript method to allow for comma seperated values in the ValidationGroup property:
function IsValidationGroupMatch(control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
}
//return (controlGroup == validationGroup);
var controlValidationGroups = controlGroup.split(",");
return (controlValidationGroups.indexOf(validationGroup) > -1);
}
Then in the ASP you add:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ValidationGroup="VG1,VG2" Display="Dynamic">
Text box is required
</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Validate VG1"
OnClick="Button1_Click" ValidationGroup="VG1" />
<asp:Button ID="Button2" runat="server" Text="Validate VG2"
OnClick="Button2_Click" ValidationGroup="VG2" />
This works on the client, but on the server you would need to add custom line(s) of code to ensure the controls listed as needing to be validated by both are checked:
// controls listed as part of ValidationGroup 'VG1' will have had their
// validation tested, ones listed as 'VG1,VG2', 'VG2,VG1' etc would not
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate("VG1,VG2");
if (!Page.IsValid)
return;
// do something
}
This way the validation controls are only needed to be added once but can be implemented for multiple ValidationGroups. It's really only a workaround/hack that works on the client, the extra checks on the all-important server side validation will need to be done manually each time.

ASP.NET Validation Group Firing Without Being Called

This is the issue I have going right now with validation controls and I simply can't find answer anywhere for it.
I currently have a required field validator watching a listbox. The validator's initial value property is set to "None". The first item in the listbox's value is also set to "None", thus forcing the user to change the selection. However I don't want the validation to show on the selected index change, I want it to show after a button press. So I changed the validation group of the validator and the button to "final" however the validator still shows on selected index changed without the button being pressed.
My code on the validator:
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Please Select an Incident" ControlToValidate="lstIncidents"
ValidationGroup="final" CssClass="style3" InitialValue="None" Display="Dynamic">
</asp:RequiredFieldValidator>
My Code on the Submit Button:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="final"
Enabled="False" />
Anyone see what might be wrong here?
Thanks in advance!
Set the validator's EnableClientScript to false (default is true):
<asp:RequiredFieldValidator EnableClientScript="False" ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Please Select an Incident" ControlToValidate="lstIncidents"
ValidationGroup="final" CssClass="style3" InitialValue="None" Display="Dynamic">
</asp:RequiredFieldValidator>

"Server Tag Not Well Formed" error in Validation Control

I got this error when I placed the unique id of the control in the source code. Below is the source code.
<ucPopupMember:PopupMember ID="PopupMember_MemberID"
runat="server"
TextBoxMaxLength="12"
ValidationGroup="SpkrSetupGroup"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator_MemberID"
runat="server"
ErrorMessage="Member ID is required"
Text="*"
CssClass="errorlabel"
ValidationGroup="SpkrSetupGroup"
Display="Dynamic"
ControlToValidate="ctl00$ContentPlaceHolder_MainContent$TabContainer1$TabPanel_Entry$PopupMember_MemberID$TextBox_MemberCode"/>
How to I change this or fix this? I'm having problems because of the "$" sign.
[UPDATE] The control to validate (textbox) is inside the user control.
You need to specify the "server" ID of the control for the ControlToValidate property. Both controls need to exist in the same container.
In the PopupMember control add the validator there:
<asp:RequiredFieldValidator ID="RequiredFieldValidator_MemberID"
runat="server"
ErrorMessage="Member ID is required"
Text="*"
CssClass="errorlabel"
ValidationGroup="SpkrSetupGroup"
Display="Dynamic"
ControlToValidate="MemberCode"/>
I suppose the member code is always required so you don't have to anything more.
But if the MemberCode sometimes is not required, add a property in the code behind of the PopupMember control.
public bool MemberRequired
{
set {RequiredFieldValidator_MemberID.Visible = value;}
}
By default is required. If you don't need it required by default use in markup Visible="false"
Apart from what #Adrian suggested, I think the Beginning and Ending should look like this:
<asp:RequiredFieldValidator>
</asp:RequiredFieldValidator>

validate a textbox value for the current date in asp.net

i have a calendar control whose value will be displayed in a textbox, i need to validate the textbox value to the current date... It should not be less than current date.....
Thanks for ur valuable reply for my last post
You can use the CompareValidator control, like this:
<asp:CompareValidator ID="dateValidator"
ControlToValidate="IdOfTextBox"
Text="error message"
Operator="GreaterThanEqual"
Type="Date"
runat="server" />
And in the code-behind, set the ValueToCompare property of the validator to DateTime.Today (for example in the Page_Init method).
Try This in Code Behind :
<asp:CompareValidator ID="CompareValidator2" runat="server" ErrorMessage="Date Should be Greater Than Current Date"
ControlToValidate="txt_DateFrom" ValuetoCompare='<%# DateTime.Now.ToString("d") %>' SetFocusOnError="true" Display="Dynamic" />
Use CompareValidator control, set properties as below:
operator = GreaterThanEqual
Type = Date
ValueToCompare = CurrentDate

Required field validator not working

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>

Resources