I've got a drop-down where the user selects a Country. It is a required "field".
Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.
Example code:
<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
runat="server" Display="Static" ErrorMessage="Required field" />
<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
runat="server" Display="Static" ErrorMessage="Required field" />
<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
runat="server" Display="Static" ErrorMessage="Required field" />
My question to you is: How can I make this CustomValidator fire validation when it is empty?
Or put simplier: How can I make a RequiredValidator fire conditionally?
Or simplest: How can I enable/disable a RequiredValidator on client-side?
Try doing this with javascript to enable and disable validators
ValidatorEnable(RequiredFieldValidatorId, false);
Check out this question that I answered.
Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,
ValidatorEnable(RequiredFieldValidatorId, false);
you can call it simply using javascript, you must send the validator object to the function (not only its id).
if (x==y) {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);
} else {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
}
or
if (x==y) {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);
} else {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
}
full documnet on:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.
(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.
if (IsPostBack){
if (x==y) {
rfvFamily.Enabled = false;
}
}
Related
there are 3 validators on an textbox,
asp:RegularExpressionValidator
asp:RangeValidator
asp:CompareValidator
some input will trigger all 3 of them, how can I stop firing the rest upon any error?
May be this can help you.. you can intercept ValidatorValidate method of ASP.Net validation framework and selectively disabled the validator controls you want based on any given validation control result.
<asp:TextBox ID="tbText" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator EnableClientScript="true" ValidationExpression="\d" ID="rang" runat="server" ControlToValidate="tbText" >sdfsdfsdfsdfsdfsd</asp:RegularExpressionValidator>
<asp:RangeValidator EnableClientScript="true" Type="Date" MinimumValue="10/10/2000" MaximumValue="10/10/2013" runat="server" ID="rang2" ControlToValidate="tbText" >23444444444444</asp:RangeValidator>
<asp:Button ID="btn" runat="server" Text="submit"/>
<script language="javascript">
var oldValidatorValidate = ValidatorValidate;
function MyValidatorValidate(val, validationGroup, event) {
//first call the original one
oldValidatorValidate(val, validationGroup, event);
//Here you can check val.isvalid - e.g write your logic here, like check for the correct validator etc etc
//alert(val.id + ":" + val.isvalid);
if (!val.isvalid) {
var myVal = document.getElementById('<%=rang2.ClientID %>');
//ValidatorEnable(myVal, false);
}
}
ValidatorValidate = MyValidatorValidate;
</script>
Arg. Inheriting projects is SO much fun. Especially when they don't work well, and even more especially when they contain UpdatePanels...
I have a shipping address user control inside an UpdatePanel. We need to be able to process international addresses, so one thing I've done is show/hide the State dropdown depending on if the country selected is US or not. In addition, I have a RequiredFieldValidator on that dropdown.
When the user control is used on a normal page elsewhere in the application, everything is great. However, in the UpdatePanel, .NET is not seeing the RFV even though JavaScript does.
Address.ascx: (snipped)
<li class="form-list-question question-state">
<span class="form-label">
<asp:Label ID="lblState" runat="server" SkinID="FieldLabel" AssociatedControlID="ddlState" Text="State" /></span>
<asp:DropDownList ID="ddlState" runat="server" SkinID="State" DataSourceID="dsStates" AppendDataBoundItems="true" ViewStateMode="Enabled"
DataTextField="Name" DataValueField="Abbr" CssClass="required">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvState" runat="server" EnableClientScript="true" Display="None" ControlToValidate="ddlState"
ErrorMessage="State is required." ValidationGroup="Address" />
</li>
address.js: (snipped)
function SetFormByCountry() {
if (isUsTerritory()) {
$('.question-state').show();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = true;
}
} else {
$('.question-state').hide();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = false;
}
}
}
Current behavior: When a country other than the US is selected, the State dropdown disappears as appropriate, but when the form is submitted, validation still occurs on the now hidden dropdown. There are no JS errors created.
Expected behavior: Given the above scenario, the RequiredFieldValidator should be disabled and the form should post.
Have you tried using the ValidatorEnable function?
It's an ASP.Net javascript function that can be used to turn off client side validators; in your example, you should be able to do the following in your client side javascript (where you set the enabled property):
ValidatorEnable(document.getElementById('<%=rfvState.ClientID%>'), false);
My only other suggestion is to fire a async postback when the country is changed and remove the state validator server side.
I have an asp.net web for with a few Validation controls on:
<div class="form-row">
<label>Email</label>
<asp:TextBox ID="txtUserName1" runat="server" onchange="validate(this)"> </asp:TextBox>
<asp:RequiredFieldValidator ID="reqUserName1" runat="server" ControlToValidate="txtUserName1"
ErrorMessage="- The email address field is required" Text="*" CssClass="error_star" Width="10px" ValidationGroup="Register"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" CssClass="error_star" runat="server" ErrorMessage="- Invalid Email Address" Text="*"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtUserName1"
ValidationGroup="Register"></asp:RegularExpressionValidator>
</div>
I have a button to submit the form
<asp:Button ID="cmdSubmit" runat="server" Text="Create Account" CssClass="small-button"
ValidationGroup="Register" CausesValidation="true" OnClientClick="validateForm()" OnClick="cmdSubmit_Click" />
The first time I hit the button some client side validation is run and my validateForm() method is not hit. for subsequent times I click the submit button my custom validation works fine.
How do I attach some custom JavaScript to the client side validation?
here' the javascript
function validateForm() {
$("input[type=text], input[type=password]", "#registerForm").each(function () {
validate(this)
});
}
function validate(control) {
// Change the colour of the border
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.style.border = "1px solid red"
return;
}
}
control.style.border = "1px solid #E1D7CE"
}
The page wasn't validating, so the javascript was working but it thought all the controls where valid, I added this
if (!Page_ClientValidate("Register")) {
Page_ClientValidate("Register")
}
to validate the page.
You can use a custom validator
http://asp.net-tutorials.com/validation/custom-validator/
they work just like any other asp.net validators, accept you get to write the function that handles the validation and sets IsValid flag. This will in turn allow/prevent postback to occur.
1- use CustomValidator, hence all you validation logic will reside in your JavaScript Code, lets say you want to validate TextBox for number > 12, javascript code would be like:
function Validate(src, eventargs)
{
var control = Document.GetElementByID(src);
if(control.value > 12)
eventargs.IsValid = true;
else
eventargs.IsValid = false;
}
2- Use CustomValidator's ClientValidationFunctionProperty set to ="Validate" (the JavaScript Function)
when you try to do any postback, then the Page.Validators collection is evaluated and so your CustomValidator
I want to code a function in javascript that every time I call it in the webform it fires up an specific validator in that same webform.
<asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server"
ErrorMessage="* Password Required!"
EnableClientScript="true" CssClass="errorText"
ControlToValidate="passwordTextBox">
</asp:RequiredFieldValidator>
To fire this validator use:
window.ValidatorValidate(window.passwordRequiredFieldValidator);
Further example:
function ValidatePassword() {
window.ValidatorValidate(window.passwordRequiredFieldValidator);
var valid = window.passwordRequiredFieldValidator.isvalid;
alert(valid);
}
if (Page_ClientValidate('Validation Group'))
{
//Your valid
}
The "CustomValidator" control lets you use javascript to validate your form. If you do this you should also do the same validation on the server so that the user can't just disable javascript to bypass the validation errors.
I have a textbox in an aspx page that has a TextChanged event attached to it.
I also have a validator attached to the textbox.
When the text is changed, the validate triggers but in case there is an error the textchanged event is still called. Do you know if it's possible to stop the postback on textchanged if the validator fires?
<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqQuantity" ControlToValidate="txtQuantity" runat="server" ErrorMessage="The quantity is mandatory."></asp:RequiredFieldValidator>
You can move validation to client side adding EnableClientScript="true" attribute. Postback won't occur as check will be performed with JS.
Other than that you can check whether page is valid when performing callback function for TextChanged event so that to define whether function can proceed. You should add ValidationGroup attribute to your validator and call Page.Validate function specifying that group before Page.IsValid is checked.
Upd
Here's the tip.
Add your own JS function, e.g.:
function IsValid( args ) {
if( args.value.length == 0 ) {
return false;
}
else {
return true;
}
}
In Page_Load event add this code:
txtQuantity.Attributes[ "onchange" ] = "if ( IsValid(this) == false ) return;";
This won't mess up auto postback when input is correct, but will prevent postback otherwise.
Add CausesValidation="true" for the text box and it will be good. If the validation is not valid there won't be any post-back.
<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged" CausesValidation="true"></asp:TextBox>
Just sharing an inline, shorter version of the accepted answer:
<asp:TextBox ID="txtQuantity" runat="server"
AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"
onchange="if (this.value.length == 0) return;"></asp:TextBox>
Having the same problem with a RequiredFieldValidator, the above worked for me.
Known nag: the designer complains that "onchange" is not a valid server-side attribute.
try it after change AutoPostBack="true" as AutoPostBack="false"..
What I do is in my client validation function I test the event type I am in. If the event shows me in a change event, I claim the validation passed and leave.
if (event.type === 'change') {
args.IsValid.true;
return;
}
I believe this is the best solution as you can leave the validator wired up and the textbox set as you like and no longer worry about the change event causing the validation.