CustomValidator with Parameters

2.7k views Asked by At

I'm validating a TextBox with a CustomValidator and JavaScript, passing it some paramaters:

<asp:CustomValidator ID="CustomValidator1" runat="server" SetFocusOnError="true" Display="Dynamic" ValidateEmptyText="true" ControlToValidate="tbFirstName" ClientValidationFunction="CVH.createFunction(notEmpty, 'tbFirstName','tbFirstNameRequired')"></asp:CustomValidator>

This is my JavaScript

var CVH = {
    createFunction: function (validationFunction, extParamOne, extParamTwo) {
        var originalFunction = validationFunction;
        var extOne = extParamOne;
        var extTwo = extParamTwo;

        return function (src, args) {
            return originalFunction(src, args, extOne, extTwo);
        }
    }
}
var CustomValidatorHelper = CVH;

function notEmpty(source, args, tbID, spID)
{
    var textBoxId = document.getElementById(tbID);
    var spanID = document.getElementById(spID);

    if (textBoxId.Value == null || textBoxId.Value == "") {
        textBoxId.IsValid = false;
        textBoxId.className = "form-control redBorder"
        spanID.className = "redText";
        alert(textBoxId.getAttribute('value'));
    }
    else {
        textBoxId.IsValid = true;
        textBoxId.className = "form-control"
        spanID.className = "";
        alert(textBoxId.getAttribute('value'));
    }
}

So notEmpty is being called correctly and it is receiving the values for tbID and spID.

Problem is, when I do enter data in the TextBox and the code is executed, I still get not value. As in textBoxId.Value is NULL even with data in the box.

TextBox ID is correct

Not valid?

The Texbox is set to Static:

<asp:TextBox ID="tbFirstName" runat="server" class="form-control" autocomplete="name" MaxLength="20" ClientIDMode="Static" />

And it's rendering correctly: <input name="ctl00$MainContent$tbFirstName" type="text" maxlength="20" id="tbFirstName" class="form-control" autocomplete="name" />

Any suggestions as to why it can't read the data in the TextBox?

1

There are 1 answers

0
Diomedes On BEST ANSWER

So the error was in trying to check the value of textbox directly as opposed of using args:

function notEmpty(source, args, tbID, spID)
{
    var textBoxId = document.getElementById(tbID);
    var spanID = document.getElementById(spID);

    if (args.Value == "")
    {
        args.IsValid = false;
        textBoxId.IsValid = false;
        textBoxId.className = "form-control redBorder"
        spanID.className = "redText";
    }
    else
    {
        args.IsValid = true;
        textBoxId.IsValid = true;
        textBoxId.className = "form-control"
        spanID.className = "";
    }
}

So the code is still the same, for exception of changing textbox.value for args.value.