Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net - manually run client-side validation code from another event

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&amp;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.

like image 913
sennett Avatar asked May 16 '12 20:05

sennett


2 Answers

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;
}
like image 50
sennett Avatar answered Oct 14 '22 16:10

sennett


thx sennett (voted)

i just ran the simplest JS

Page_ClientValidate();

if you have a validation group then is

Page_ClientValidate("validationGroupName")
like image 38
bresleveloper Avatar answered Oct 14 '22 17:10

bresleveloper