Validating Textbox with CustomValidator's ClientValidationFunction not firing - javascript

I am having some serious issues with this. I have a two fields like this, both of them being assigned datepickers with jquery.
<asp:TextBox ID="RTRP" runat="server" CssClass="textEntry" Width="120"></asp:TextBox>
<asp:CustomValidator runat="server" ID="CustomValidator3"
ControlToValidate="RTRP"
Text="No date selected"
ValidateEmptyText="True"
ClientValidationFunction="clientValidate"
Display="Static">
</asp:CustomValidator>
<asp:TextBox ID="ContEd" runat="server" CssClass="textEntry" Width="120"></asp:TextBox>
<asp:CustomValidator runat="server" ID="CustomValidator1"
ControlToValidate="ContEd"
Text="No date selected"
ValidateEmptyText="True"
ClientValidationFunction="clientValidate"
Display="Static">
</asp:CustomValidator>
With the following javascript to validate it.
$("#<%=RTRP.ClientID %>").datepicker();
$("#<%=ContEd.ClientID %>").datepicker();
function clientValidate(sender, args) {
args.IsValid = args.Value.length > 0;
}
Both get their datepickers, but the validation function simply refuses to be fired and always allows the form to submit. I am completely lost here, what am I doing wrong?

You are checking if a string's length is less than 0 (what is never true) here:
function clientValidate(sender, args) {
if (args.Value.length < 0) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
I'm not sure if this is what you want(you could simpy use a RequiredFieldValidator), but...
function clientValidate(sender, args) {
args.IsValid = args.Value.length > 0;
}

If you assign $.datepicker() behaviour to any text, and run page.. you will find that textbox on which you override jQuery datepicker had css set display : none.. so that might be the reason that custom validation not getting for that textbox...

why dont you use
<asp:RequiredFieldValidator id="id" controltovalidate="controlname" erormessage="please enter the dates">
</asp:RequiredFieldValidator>
correct me i am wrong

Change you method to this.and try again
function clientValidate(sender, args)
{
if(Page_ClientValidate())
{
if (args.Value.length < 0)
{
args.IsValid = false;
} else
{
args.IsValid = true;
}
}
}

Related

Avoid duplicated error messages with ASP.NET CustomValidator

I have an ASP.NET page defined in this way:
<asp:TextBox
ID="_txtExitDate"
ClientIDMode="Static"
runat="server"
Text='<%#Bind("exit_date","{0:dd/MM/yyyy}")%>'
placeholder="gg/mm/aaaa" />
<asp:CompareValidator
runat = "server"
Type = "Date"
Operator = "DataTypeCheck"
Display = "Dynamic"
ControlToValidate = "_txtExitDate"
ErrorMessage = "Exit date invalid."
SetFocusOnError = "true" />
<asp:CustomValidator
Display="Dynamic"
runat="server"
EnableClientScript="true"
ClientValidationFunction="Validate_Exit"
ControlToValidate="_txtExitDate"
ErrorMessage="Exit date should be minor of today date." />
<asp:TextBox
ID="_txtExitTime"
ClientIDMode="Static"
CssClass="input_small"
runat="server"
Text='<%#Bind("exit_time")%>'
placeholder="hh:mm" />
<asp:RegularExpressionValidator
Display = "Dynamic"
ControlToValidate="_txtExitTime"
runat="server"
ErrorMessage="Exit time invalid"
ValidationExpression="^([01][0-9]|2[0-3]|[1-9]):([0-5][0-9]|[0-9])$"
SetFocusOnError = "true" />
<asp:CustomValidator
Display="Dynamic"
runat="server"
EnableClientScript="true"
ClientValidationFunction="Validate_Exit"
ControlToValidate="_txtExitTime"
ErrorMessage="Exit date should be minor of today date." />
The Javascript code that evaluates CustomValidators is:
function Validate_Exit(sender, args) {
var _txtExitDate = $("input[id$='_txtExitDate ']");
var _txtExitTime = $("input[id$='_txtExitTime ']");
if (isBlank(_txtExitDate.val()) || isBlank(_txtExitTime.val())) {
args.IsValid = true;
return;
}
var _sExit = _txtExitDate .val().substring(0, 10) + " " + _txtExitTime.val().substring(0, 5);
var _exit = moment(_sExit, "DD/MM/YYYY HH:mm:ss");
if (_exit.isAfter(moment())) {
args.IsValid = false;
return;
}
args.IsValid = true;
}
The scope of the form is to allow the user to input only valid date/time values. In particular the CustomValidator is intended to allow the input of a couple of combined values that should be minor of the present date-time.
It works as I expect except for a side effect that it's not compromising but it's graphically annoying.
As you can see the CustomValidator is basically the same and it's applied to both textboxes. If the user fails to write a correct date / time combo it show off the message (that's the same message because it's referred to the composed date/time value). In some case the error message is shown 'twice' and this is in part (graphically) horrible but also a little confusing for the user.
Is there a way to avoid duplicating this check and to provide a control for both textboxes so the user is not confused by a double error message?
Best regards,
Mike
You can use a single CustomValidator to validate both fields. Set the ID of that validator but don't set the ControlToValidate property (here I also set the Text property to show an indicator even when the postback is not triggered):
<asp:CustomValidator
ID="cvDateTime"
Display="Dynamic"
runat="server"
Text="Invalid date!"
EnableClientScript="true"
ClientValidationFunction="Validate_Exit"
ErrorMessage="Exit date should be minor of today date." />
You can set the onchange event handler on both TextBoxes to perform the validation as soon as each field is modified:
<asp:TextBox ID="_txtExitDate" onchange="ValidateOnChange();" ... />
<asp:TextBox ID="_txtExitTime" onchange="ValidateOnChange();" ... />
The validation functions could look like this:
function ValidateOnChange() {
var validator = document.getElementById('<%= cvDateTime.ClientID %>');
validator.isvalid = DoValidateDateTime();
ValidatorUpdateDisplay(validator)
}
function Validate_Exit(source, args) {
args.IsValid = DoValidateDateTime();
}
function DoValidateDateTime() {
var _txtExitDate = $("input[id$='_txtExitDate ']");
var _txtExitTime = $("input[id$='_txtExitTime ']");
if (isBlank(_txtExitDate.val()) || isBlank(_txtExitTime.val())) {
return true;
}
var _sExit = _txtExitDate .val().substring(0, 10) + " " + _txtExitTime.val().substring(0, 5);
var _exit = moment(_sExit, "DD/MM/YYYY HH:mm:ss");
return _exit.isSameOrBefore(moment());
}

Select text of the control when validation occurs

I want to highlight text in control when validation occurs.
How can I achieve this?
<script language="javascript" type="text/javascript">
function changeColor(source, args) {
var txt = document.getElementById('<%= txtAge.ClientID %>');
if (args.Value.length >= 3) {
txt.style.background = '#66CCFF';
args.IsValid = false;
}
else {
txt.style.background = 'none';
args.IsValid = true;
}
}
</script>
<asp:TextBox ID="txtAge" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfldtxtAge" ErrorMessage="enter the value" ControlToValidate="txtAge" runat="server" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="ctmtxtAge" runat="server" ClientValidationFunction="changeColor" ControlToValidate="txtAge" ErrorMessage="CustomValidator1" ></asp:CustomValidator>
I use this code for highlighting background of control, but I need to highlight the text of control.
Please help me.
Please use
txt.select();
instead of
txt.style.background = '#66CCFF';
please let me know if this does not work.
txt.style.color= '#66CCFF' instead of txt.style.background = '#66CCFF';
use this thing to change the color of the text

ASP.net CustomValidator - ClientValidationFunction to check value not blank and not initial value

I have following code which validates the value of a textbox to make sure it's not blank but I also need to check that it does not equal the initial value of the textbox (defaultValue).
Here's what I have so far...
Javascript:
function textValidation(source, arguments)
{
if ( arguments.Value != "" ){ // && arguments.Value != arguments.defaultValue
arguments.IsValid = true;
} else {
$(source).parents("div").css({"background-color":"red"});
arguments.IsValid = false;
}
}
.net
<asp:TextBox runat="server" ID="Initial" Text="Initial" defaultValue="Initial" Width="120px" />
<asp:CustomValidator id="Initial_req"
ControlToValidate="Initial"
ClientValidationFunction="textValidation"
ValidateEmptyText="true"
runat="server"
CssClass="errorAsterisk"
Text="*"
ErrorMessage="Complete all correspondence fields" />
You can do what you want using a CSS class to identify the TextBox and retrieve it with jQuery, allowing you to obtain the attribute defaultValue:
Markup:
<asp:TextBox runat="server"
ID="Initial"
Text="Initial"
defaultValue="Initial"
Width="120px"
ValidationGroup="Test"
CssClass="to-validate" />
<asp:CustomValidator ID="Initial_req"
ControlToValidate="Initial"
ClientValidationFunction="textValidation"
ValidateEmptyText="true"
runat="server"
CssClass="errorAsterisk"
Text="*"
ErrorMessage="Complete all correspondence fields"
ValidationGroup="Test" />
<asp:Button ID="btnValidate" runat="server" Text="Validate" ValidationGroup="Test" />
Javascript:
function textValidation(source, arguments) {
var initialValue = $(source).siblings(".to-validate:first").attr("defaultValue");
if (arguments.Value != "" && arguments.Value != initialValue) { // && arguments.Value != arguments.defaultValue
arguments.IsValid = true;
} else {
$(source).parents("div").css({ "background-color": "red" });
arguments.IsValid = false;
}
}
1)You not pass source and arguments parameters in your function .
2) then call this syntax way for ClientValidationFunction="javascript:textValidation(param1,oaram2);return true;"
3)you can use required field validation in text box here
4)or another way is (we dont use any parameter ) for here
A RequiredFieldValidator will prevent blanks as well as initial values.
Use attribute InitialValue.
See here:
Use it to prevent any value that you like being entered into a TextBox. The TextBox doesn't have to have that value embedded at the start - it just can't be submitted with that value.

ASP.NET Password and Confirmation in ClientSideEvents

I have 2 ASPxTextBox, ASPxValidationSummary and ASPxButton
In JS file there is OnPasswordValidation function
But when i type a password then click Tab button the SetIsValid(false)
on txt_password control doesn't work but it work on txt_ConfirmPassword
Why ?
<dx:ASPxTextBox ID="txt_password" runat="server" Password="true" AssociatedControlID="txt_password">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="txt_ConfirmPassword" runat="server" Password="true" AssociatedControlID="txt_ConfirmPassword">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit" ClientInstanceName="btnSubmit" onclick="btnSubmit_Click" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {onClickBtnSubmit();}"/>
</dx:ASPxButton>
function OnPasswordValidation(s, e) {
var objpassword = GetObj('txt_password');
var objConfirmPassword = GetObj('txt_ConfirmPassword');
var password = aspxGetControlCollection().Get(objpassword.id);
var ConfirmPassword = aspxGetControlCollection().Get(objConfirmPassword.id);
if (password.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (ConfirmPassword.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (password.GetValue().length > 5 || ConfirmPassword.GetValue().length > 5) {
if (password.GetValue() == ConfirmPassword.GetValue()) {
password.SetIsValid(true);
ConfirmPassword.SetIsValid(true);
}
else {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
password.SetErrorText = "Password must equal with Confirm Password";
ConfirmPassword.SetErrorText = "Password must equal with Confirm Password";
}
}
else {
ConfirmPassword.SetIsValid(false);
password.SetIsValid(false);
}
}
This is not a proper way to implement validation. This way OnPasswordValidation function is executed twice, once for every textbox.
Here is a ticket with sample project that should do what you need:
http://www.devexpress.com/Support/Center/p/Q233058.aspx
I advice you to read DevExpress controls validation overview in order to understand how to implement validation on devex controls.

check box validation for atleast one check box should cheked in asp.net

I have asp.net form having 4 check boxes. not check box list. these 4 check boxes having the ValidationGroup property with same name say "chkValied". I have added Custom Validator there. now want to check at least on check box should be check out of these. what to do ?
You can use CustomValidator to validate input at client-side or server-side code.
aspx markup
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<asp:CheckBox ID="CheckBox4" runat="server" />
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="put here error description"
ClientValidationFunction="clientfunc"
OnServerValidate="CheckValidate">
</asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
.cs (code-behind)
protected void CheckValidate(object source, ServerValidateEventArgs args)
{
args.IsValid=false;
if (CheckBox1.Checked)
args.IsValid = true;
if (CheckBox2.Checked)
args.IsValid = true;
if (CheckBox3.Checked)
args.IsValid = true;
if (CheckBox4.Checked)
args.IsValid = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
//valid
}
else
{
//Invalid
}
}
JavaScript code
<script type="text/javascript">
function clientfunc(sender, args) {
args.IsValid = false;
if (document.getElementById("CheckBox1").checked)
args.IsValid = true;
if (document.getElementById("CheckBox2").checked)
args.IsValid = true;
if (document.getElementById("CheckBox3").checked)
args.IsValid = true;
if (document.getElementById("CheckBox4").checked)
args.IsValid = true;
}
</script>
Try this article
http://weblogs.asp.net/samirgeorge/archive/2009/05/02/checkboxlist-client-side-validation-using-jquery.aspx
https://web.archive.org/web/20211020153246/https://www.4guysfromrolla.com/webtech/tips/t040302-1.shtml
If you are using custom validator such thing could be achieved with an or-statement:
if (chkBox1.Checked || chkBox2.Checked || chkBox3.Checked)
{
// At least 1 checkbox was checked.
}
This applies to all languages (although || is not universal all languages has a representation of it). In JavaScript you'd want .Value instead of .Checked.

Categories

Resources