ASP.net Custom Validator message not displaying - asp.net

I have a div which acts like a modal popup. Inside that, I need a validation for which I setup a custom validator. But the message doesn't get fired, though the alert box does.
My code:
if ((oldFromTime <= newFromTime) && (oldToTime > newFromTime)) {
alert("Choose time ahead of the ones saved earlier.!");
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
And my custom validator
<asp:CustomValidator id="cboToTimeMins_CustomValidator" ControlToValidate="cboToTimeMins" ClientValidationFunction="validateTime"
Display="static" ErrorMessage="Selected time range falls in the range of the ones saved earlier...! Choose another." runat="server" ValidationGroup="Timetable"/>
cboToTimeMins is my dropdown box, and I need to set the validation message based on the value selected from it.
Is there something wrong in my code?
P.S. I am in need of only CLIENT SIDE validation.

Here's my solution. I removed the custom validator for the Dropdown and added it to a button instead. Also, I removed the alert message in the Javascript function.

Here's my example solution
<td class="normal">Price<span class="required">*</span></td>
<td class="normal" colspan="6">
<asp:TextBox ID="txtPrice" CssClass="text" Enabled="true" runat="server" MaxLength="10" Width="100px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPrice"
ErrorMessage="* Please Input Your Price" Display="Dynamic" ValidationGroup="hdrValidation"/>
</td>
And you need to validate
Page.Validate("hdrValidation")
If Not Page.IsValid Then Exit Sub

Related

How can I achieve the effect of multiple validation groups on a single validation control?

I need to be able to apply multiple validation groups to some of the controls on my page, because for each of the three submit "modes", there is a different set of required fields.
I have three submit buttons, and each one has its own validation group (reject, approve, and save). "Reject" doesn't actually have any required fields currently, but may in the future. "Save" only requires "first name" and "last name", while "approve" requires "first name", "last name", as well as "group name".
I tried simply putting multiple validation groups in the attribute value (as in the code below), but the validation didn't fire at all.
I also tried not specifying a group at all in an attempt to just have the validation always fire, but again again, it didn't fire at all.
<div>
<label for='<%= txt_FirstName.ClientID %>'>First Name</label>
<asp:TextBox ID="txt_FirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv_FirstName" runat="server" text="Required"
ControlToValidate="txt_FirstName" ValidationGroup="approve save">
</asp:RequiredFieldValidator>
</div>
<div>
<label for='<%= txt_LastName.ClientID %>'>Last Name</label>
<asp:TextBox ID="txt_LastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv_LastName" runat="server" text="Required"
ControlToValidate="txt_LastName" ValidationGroup="approve save">
</asp:RequiredFieldValidator>
</div>
<div>
<label for='<%= ddl_GroupName.ClientID %>'>Group Name</label>
<asp:DropDownList ID="ddl_GroupName" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv_GroupName" runat="server" text="Required"
ControlToValidate="ddl_GroupName" ValidationGroup="approve">
</asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="btn_Reject" runat="server" Text="Reject"
ValidationGroup="reject" OnClick="btn_Reject_Click" />
<asp:Button ID="btn_Approve" runat="server" Text="Approve"
ValidationGroup="approve" OnClick="btn_Approve_Click" />
<asp:Button ID="btn_Save" runat="server" Text="Save"
ValidationGroup="save" OnClick="btn_Save_Click" />
</div>
I'm certain I can achieve the desired effect with some additional code, or duplicated validator controls for each validation group, but I was hoping the webforms framework would have a simpler, built-in way to do this.
UPDATE (2018-01-02):
The question "Is it possible to assign Multiple Validation Groups to a single Validation Control?" is a special case of my own. It has a single control in multiple groups, whereas I have multiple controls with multiple overlapping groups. Additionally, the answer proposes having a validation control for each input/group combination. This is a terrible solution because, among other things, it violates the DRY (don't repeat yourself) programming principle and makes maintenance/enhancements more difficult.
The above also links the question "How to validate against Multiple validation groups?". That question is a completely different issue (validation groups within validation groups), and its answer proposes custom javascript that would need to be written for every submit button, on every page that requires multiple validation groups.
I am looking for a general case solution that I can write/implement once and apply to the entirety of the web application, and thus I do not consider my question a duplicate of the above mentioned questions.
UPDATE (2018-01-03):
Between other questions/articles I've encountered while researching my problem, as well as the gracious assistance of a.bajorinas and Sunil, I've established that it is not possible to have multiple validation groups on a validation control out-of-the-box, and custom code will be required to achieve the desired effect. I've updated the question accordingly, to assist anyone looking to achieve this in the future.
I'll be testing a solution that incorporates elements from both a.bajorinas' and Sunil's answers and will hopefully be able to provide an update afterward.
The only thing I can think of for your desired use case, is setting ValidationGroup for your validators in code behind on button click, keep in mind that this would first perform a postback and then validate the controls which might not be ok for you.
protected void btn_save_click(object sender, EventArgs e){
rfv_FirstName.ValidationGroup = "save";
Page.Validate("save");
if (Page.IsValid)
{
//logic if validators pass
}
}
This will let you reuse validators for multiple groups.
Also in my linked posted, one of the comments to the selected answer is "It is not possible to assign multiple groups to a validation control"
ASP.Net does not support multiple validation groups. However, with a little bit of JavaScript code you can make it support multiple validation groups.
What you need to do is override the standard JavaScript function of IsValidationGroupMatch. This function is part of the standard validation library in ASP.Net.
At bottom of your aspx page, just add the script tag given below. Note that this script is just before closing form, body and html tags, which is important when overriding a JavaScript function.
<script type="text/javascript">
window["IsValidationGroupMatch"] = function (control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
var isGroupContained = false;
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
var controlGroupArray = [];
if (validationGroup.indexOf(",") > -1) {
controlGroupArray = validationGroup.split(",");// validationGroup.split(",");
}
for (var i = 0; i < controlGroupArray.length; i++) {
if (controlGroupArray[i].trim() == controlGroup.trim()) {
isGroupContained = true;
}
}
}
return (controlGroup == validationGroup || isGroupContained);
}
</script>
</form>
</body>
</html>
Once you do this, then you can add a comma delimited list of validation groups for the button that validates multiple validation groups as in example below. In example below a button with id of btnMultipleValidationGroups is validating group1 as well as group2.
<div>
TextBox1 :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 needs input" ControlToValidate="TextBox1" ForeColor="Red" ValidationGroup="group1"></asp:RequiredFieldValidator>
<br />
<br />
TextBox2 :
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="TextBox2 needs input" ControlToValidate="TextBox2" ForeColor="Red" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
<br />
TextBox3 :
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="TextBox3 needs input" ControlToValidate="TextBox3" ForeColor="Red" ValidationGroup="group3"></asp:RequiredFieldValidator>
<br />
<br />
</div>
<asp:Button ID="btnMultipleValidationGroups" runat="server" Text="Validate group1 and group2" ValidationGroup="group1,group2" OnClick="btnMultipleValidationGroups_Click" />
<asp:Button ID="btnGroup1" runat="server" Text="Validate only group1" ValidationGroup="group1" OnClick="btnGroup1_Click" />
<asp:Button ID="btnGroup2" runat="server" Text="Validate only group2" ValidationGroup="group2" OnClick="btnGroup2_Click" />

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 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.

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!

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