I am currently involved in developing a system using asp.net(VB). I have applied required validator so that to obtain correct inputs from user. But now I am having some issues. I also must allow the user to leave the text boxes empty too. Then can submit the page. so consider the form can validate true if thetext box are left empty or with values.
how to solve this issue frends? Kindly help me. Thank You very much
When you use a required Validator, the text will be required. Hence the name...
If you want more complex validation you need to use a CustomValidator
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Text not long enough" ValidationGroup="myGroup" ClientValidationFunction="myCustomValidation"></asp:CustomValidator>
<script type="text/javascript">
function myCustomValidation(oSrc, args) {
var textboxValue = args.Value;
if (textboxValue == "") {
args.IsValid = true;
} else {
if (textboxValue.length > 4) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
}
</script>
Related
I am trying to show an error by changing the color of the border of a text box. I have found a lot of posts on how to do it, but I have never done anything with 'Validators' so I am confused where to start, or where to put the code.
Similar posts:
Post One
Post Two
My main question(s) are, where do I put the JS code? And secondly, how do I call the code?
Current Code
If TicketNumber.Text = String.Empty = True Then
NotificationLabel.Text = "Ticket Number must be filled out"
Exit Sub
End If
A RequiredFieldValidator could do it with some tricks explained here, and here. Another way is to use a CustomValidator like the following.
aspx mark-up
<asp:TextBox runat="server" ID="tbText" />
<asp:CustomValidator ID="cvCustom" ErrorMessage="Ticket Number must be filled out"
ControlToValidate="tbText" runat="server" OnServerValidate="ValidateInput"
ClientValidationFunction="ValidateInput" ValidateEmptyText="True" />
<asp:Button Text="My Button" runat="server" />
Javascript
<script type="text/javascript">
function ValidateInput(sender, args) {
if (args.Value == '') {
args.IsValid = false;
document.getElementById('<%= tbText.ClientID %>').style.borderColor = "red";
return false;
}
return true;
}
</script>
Code Behind (C#)
protected void ValidateInput(object source, ServerValidateEventArgs args)
{
if(string.IsNullOrWhiteSpace(args.Value))
{
args.IsValid = false;
tbText.Style["border-color"] = "red";
}
else
{
args.IsValid = true;
}
}
I have an ASP.NET TextBox with a CustomValidation control that invokes client side validation script.
<asp:TextBox ID="txtSubsContrRbtAmt" runat="server"
CssClass="textEntry NumericInput" Width="150px"
Text="" onKeyUp="SumValues();" MaxLength="16"></asp:TextBox>
<asp:CustomValidator ID="cvalSubsContrRbtAmt" runat="server" ClientValidationFunction="ValidatetxtSubsContrRbtAmt"
ControlToValidate="txtSubsContrRbtAmt" CssClass="errlable" ErrorMessage="Max Decimals = 7"
SetFocusOnError="True" ValidationGroup="CarbsAdd"></asp:CustomValidator>
Here's the Client script:
function ValidatetxtSubsContrRbtAmt(source, args) {
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var amount = txtSubsContrRbtAmt.value;
args.IsValid = ValidAmount(amount);
if (!args.IsValid)
txtSubsContrRbtAmt.focus();
}
function ValidAmount(amount) {
if (isNumber(amount)) {
return (RoundToXDecimalPlaces(amount, 7) == amount);
}
else {
return true;
}
In the ValidatetxtSubsContrRbtAmt function, the "source" parameter is the CustomValidator. That control has a property "ControlToValidate." If I can get to it, I can programmatically retrieve the value from that control and not have to have a separate function to validate each textbox.
jQuery is too much for me at this point, I'm looking for a plain old Javascript approach, please.
You don't have to get the text box. You can get the value from args.Value. The focus should be set automatically if you set SetFocusOnError="true".
function ValidatetxtSubsContrRbtAmt(source, args) {
var amount = args.Value;
args.IsValid = ValidAmount(amount);
}
You should be able to get to the control from the source object.
function ValidatetxtSubsContrRbtAmt(source, args) {
var controlToFocusOn = source.ControlToValidate;
you can switch that out with "document.getElementByID()" to get the ID or whatever attribute you need
var controlId = document.getElementById(source.ControlToValidate).id;
}
now you can focus or do what you need with the control. I had to access the the actual ControlToValidate earlier today from a CustomValidator.
I want to run whatever client-side validation routine is hooked up to a particular text input element.
The validation has been set up using CustomValidator:
<asp:textbox id="AddEstTime" runat="server" Width="55px"></asp:textbox><br />
<asp:CustomValidator ID="AddEstTimeCustomValidator" ClientValidationFunction="AddEstTimeCustomValidator_ClientValidate" OnServerValidate="AddEstTimeCustomValidator_ServerValidate" ErrorMessage="Please enter a time" ControlToValidate="AddEstTime" runat="server" Display="Dynamic" ValidateEmptyText="true"/>
<asp:CheckBox ID="AddIsTM" runat="server" Text="T&M" />
and the javascript:
function AddEstTimeCustomValidator_ClientValidate(sender, args) {
var checkbox = $("input[id$='IsTM']");
args.IsValid = checkbox.is(":checked") || args.Value.match(/^\d+$/);
}
When the CheckBox "AddIsTM" state changes, I want to revalidate the textbox "AddEstTime", using its hooked-up CustomValidator "AddEstTimeCustomValidator".
I am aware of focus -> add a character refocus -> remove character. I am trying to find a more correct way. New to asp.NET.
After looking through the Microsoft client-side code, I came up with this which seems to work:
// client-side validation of one user-control.
// pass in jquery object with the validation control
function ValidateOneElement(passedValidator) {
if (typeof (Page_Validators) == "undefined") {
return;
}
$.each(Page_Validators, function (index, value) {
if ($(value).attr("id") == passedValidator.attr("id")) {
ValidatorValidate(value, null, null);
}
});
}
This was after examining the Page_ClientValidate function:
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
thx sennett (voted)
i just ran the simplest JS
Page_ClientValidate();
if you have a validation group then is
Page_ClientValidate("validationGroupName")
If you want stick with ASP.NET validators eventually you can abuse Validation Groups, but I think that this approach will give you nothing but trouble. Other option is to use jQuery on the client (nice list) only then you will have to duplicate validation on the server side, or to avoid that call server methods from client validations.
I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.
I am using the AJAX Cascading drop down list but want to add event validation e.g. the compare validators.
As the cascading drop down list requires the page event validation to be disabled what is the best way to do the validation?
Thanks
Andy
Validation Attempt:
I have tried to use a custom validator which calls a Javascript function but it doesnt seem to be picking up the control. I get the following error Microsoft JScript runtime error: Object required
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("ddlCategory");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if (iValue == "Select Category")
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
}
}
The mark-up for the custom validator is
<asp:CustomValidator ID="valcustCategory" runat="server" CssClass="error" Display="Dynamic" ValidationGroup="DirectHire" ClientValidationFunction="ValidateCostCentCat"
ErrorMessage="Please select a Cost Centre Category from the drop down list provided.">!</asp:CustomValidator>
Read This: http://www.w3schools.com/PHP/php_ajax_database.asp
The example demostrate how to select a
value from a dropdown box sent it via
AJAX and get back the responce!
in the middle you can do all the
Validation that you want!
UPDATED with code just for fun! ;-)
Assuming your select is
<asp:DropDownList ID="CategoryDropDownList" runat="server">
Then you function look like this:
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("CategoryDropDownList");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if ( iValue == "Select Category" ) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
}
This must work as expected!
hope this help!