How do I fire an ASP.NET custom validator from JavaScript? - asp.net

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.

Related

How do I add custom Javascript to asp.net client side causes validation function?

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

Required Field Validations in USER CONTROL are fired in all instances of this usercontrol when it is placed multiple times in single page

I have usercontrol which has required field validation in it. I have 2 instances of this usercontrol in single web page . Now if I click button on first usercontrol the validation messages are fired for 2 user controls. But only the required fields of that user control has to be fired. Please could any one solve this problem.
Thanks
Madhavi
If you have not set the ValidationGroup property of the RequiredFieldValidator within your usercontrol then field validation will fire whenever the form is submitted regardless of which button caused the postback.
If you wish to associated specific validators with specific submit buttons then you will have to associate them to the same ValdiationGroup.
If you are setting the ValidatioGroup within your user control but finding that the validation is firing for all instances of the control then you will need to take some attribute of the user control instance and incorporate it into the ValidationGroup to ensure the user control is exclusively validated for any submit button on the control.
Here is an example:
<asp:TextBox ID="txtTest" runat="server"/>
<asp:RequiredFieldValidator ID="txtTestReqVal"
runat="server"
Display="Dynamic"
ControlToValidate="txtTest"
Text="* Field is required"
ValidationGroup="valGroup<%= ClientId %>"
CssClass="modelError"
/>
<asp:Button ID="btnSubmit" runat="server"
Text="Submit"
CausesValidation="true"
ValidationGroup="valGroup<%= ClientId %>"
/>
The trick here is the <%= ClientId %> part. This will inject the instances client side unique id into the validation group value. This means that all validation for these controls will be grouped together by the single unique instance of the user control. This way you can have multiple instances of the same user control present on the same page but all uniquely validated.
make your validation groups runat="server"
Then give each one a unique validation group like this:
string validationGroup = Guid.NewGuid().ToString();
txtContactNameValidator.ValidationGroup = validationGroup;
txtContactNumberValidator.ValidationGroup = validationGroup;
btnSave.ValidationGroup = validationGroup;
This will isolate the user controls from each other no matter how many are on the page.
I think you need to specify a validatongroup attribute on every field validation control.
Each user control would have its own validation group defined.
See here
One way to solve this is to expose a public property on your usercontrol which you can pass in the validation group name.
<uc:mycontrol id=u1 validationgroup="valA" .. />
<uc:mycontrol id=u2 validationgroup="valB" .. />
One problem with this approach is that you will need to add the validation group to every validation control within page load on the usercontrol.
I think the validation group will not work.. As it is the same user control but dropped 2 times in the page. Any of the button will fire validation on both user control wh
function ValidateRadio(button)
{
var radioOptions = document.getElementById(button.id.split("_")[0] +'_rblPollOptions');
var RVPollOptions = document.getElementById(button.id.split("_")[0] +'_RVPollOptions');
var options = radioOptions.getElementsByTagName("input");
var radioSelected=false;
for (j=0; j < options.length; j++)
{
if(options[j].checked)
{
radioSelected=true;
break; // Found it, proceed to next question
}
}
if (!radioSelected) // no option selected
{ // warn user, focus question //alert("You did not answer question");
RVPollOptions.style.visibility = "visible";
return false;
}
}
</script>
<asp:RequiredFieldValidator ID="RVPollOptions" runat="server" ControlToValidate="rblPollOptions"
ErrorMessage="Select option!"> </asp:RequiredFieldValidator>
<asp:Button ID="btnPoll" Text="Vote" OnClientClick="javascript:return ValidateRadio(this)" runat="server" OnClick="btnPoll_Click" />

Server-side validation in ASP.NET 2.0

My application is in ASP.NET 2.0 with C#. I have a regular expression validator with the regular expression ^[0-9]*(\\,)?[0-9]?[0-9]?$, now my client don't want this validation at client side but on button click i.e. Server Side.
EX: I have to check the value of txtPrice textbox
Please let me know how can I put this regular expression validation on server side.
Thanks in advance.
You can use a CustomValidator which can link to a server side event:
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" OnServerValidate="CustomValidator1_Validate"></asp:CustomValidator>
Then server side you can validate input
protected void CustomValidator1_Validate (object source, ServerValidateEventArgs argss)
{}
Remember to wrap your submit button click with
if(IsValid) {}
To ensure all validators are respected
The control will validate on the server side always, regardless of whether you also enable client-side validation. But you must then remember to check the value of Page.IsValid before accepting the postback...
As has already been said, you can turn off client-side validation with an attribute.
Try to add EnableClientScript="false" to the validator.
Client-side validation using server-side controls based on ValidatorBase takes place only on PostBack i.e. on any server-side button/linkbutton click.
So you can use RegularExpressionValidator:
<asp:TextBox runat="server" ID="txtPrice" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtPrice" ValidationExpression="^[0-9]*(\\,)?[0-9]?[0-9]?$" ErrorMessage="Input is incorrect" />
Also you can use CustomValidator:
<asp:TextBox runat="server" ID="txtPrice" />
<asp:CustomValidator runat="server" ControlToValidate="txtPrice" ErrorMessage="Input is incorrect" OnServerValidate="CustomValidator1_ServerValidate" />
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
// use e.Value to validate and set e.IsValid
// it's different depending on control to validate.
// for custom controls you can set it using ValidationPropertyAttribute
}

Enable/disable RequiredValidator on client-side / CustomValidator not firing

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;
}
}

Stop postback on TextChanged

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.

Resources