首页 文章

使用CustomValidator更改文本框的颜色

提问于
浏览
0

我正在运行时创建一些文本框,如果文本框留空并且用户提交表单,我想更改文本框的颜色 .

我正在使用代码隐藏方法,这是我在.aspx.cs文件中编写的代码

textBoxObj是我在运行时创建的文本框对象,它是我想要空验证的对象 .

CustomValidator customValidatorObj = new CustomValidator();
customValidatorObj.ControlToValidate = textBoxObj.ID;
customValidatorObj.ClientValidationFunction = "changeColorofTextBox";

我在.aspx文件中写了一个小的Javascript片段,如下所示(我还没有编写改变颜色的逻辑,只是让它现在无效)

<script type="text/javascript">
    function changeColorofTextBox(oSrc, args) {
        if (args.Value.length > 0) {
            args.IsValid = true;
        }
        else {
            args.IsValid = false;
        }
    }
</script>

在表单的提交按钮单击功能中,我检查是否(Page.IsValid),然后提交表单 . 但是,即使文本框为空,表单也会被提交 . 看起来这个功能甚至没有被击中 . 你对我做错了什么有什么指示吗?无论客户端还是服务器端验证,我都可以 .

编辑

我得到了错误,我只是必须这样做

customValidatorObj.ValidateEmptyText = true;

它开始工作..谢谢,我没有意识到customValidator类没有尝试验证控件是否为空 .

但我再次陷入困境:(

在表单中,我有很多文本框 . 假设用户输入了3个文本框的文本,并将其中2个空白,我如何找到文本框ID,以便我只能更改空白框的颜色 . 或者,如何在javascript中编写代码以在运行时找出控件ID?

我知道我们必须这样做

document.getElementById(CONTROLIDGOESHERE).style.backgroundColor =“red”;

但是我如何将CONTROLIDGOESHERE值传递给getElementById函数?

任何指针,谢谢 .

3 回答

  • 1

    尝试设置customValidatorObj.EnableClientScipt = True

  • 0

    假设您运行的是.NET Framework 4.0版,那么您可以使用ClientIDMode =“Static”声明文本框 . 这样他们将拥有相同的ID客户端和服务器端,例如

    <asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
    

    然后,您可以通过声明如下按钮来触发按钮单击时的客户端验证:

    <input type="submit" id="btnSubmit" onclick="ClientSideValidation(); return false;" value="Save"/>
    

    JavaScript函数可能如下所示:

    <script type="text/javascript">
        function ClientSideValidation() {
            var txtName = document.getElementById("txtName");
            if (txtName.value.length == 0) {
                txtName.style.background = "#DE0000";
            }
            // Check other text boxes...
        }
    </script>
    
  • 1

    谢谢你们,我想通了 . 这段代码对我有用

    .aspx.cs

    CustomValidator customValidator = new CustomValidator();
        customValidator.ControlToValidate = textBox.ID;
        customValidator.ClientValidationFunction = "changeColorofTextBox";
        customValidator.ValidateEmptyText = true;
        customValidator.EnableClientScript = true;
        e.Item.Controls.Add(customValidator);
    

    的.aspx

    <script type="text/javascript">
        function changeColorofTextBox(oSrc, args) {
            if (args.Value.length > 0) {
                args.IsValid = true;
            }
            else {
                var ctrlid = oSrc.id;
                var validatorid = document.getElementById(ctrlid);
                ctrlid = validatorid.controltovalidate;
                document.getElementById(ctrlid).style.backgroundColor = "Tomato";
                args.IsValid = false;
            }
        }
    </script>
    

相关问题