Change Text Box Color using Required Field Validator. No Extender Controls Please

前端 未结 16 2138
广开言路
广开言路 2020-11-28 07:07

I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button

相关标签:
16条回答
  • 2020-11-28 07:36

    I liked Rory's answer, but it doesn't work well with ValidationGroups, certainly in my instance where I have two validators on one field triggered by two different buttons.

    The problem is that ValidatorValidate will mark the validator as 'isValid' if it is not in the current ValidationGroup, but our class-changing code does not pay any attention. This meant the the display was not correct (certainly IE9 seems to not like to play).

    so to get around it I made the following changes:

        /**
        * Re-assigns the ASP.NET validation JS function to
        * provide a more flexible approach
        */
        function UpgradeASPNETValidation() {
            if (typeof (Page_ClientValidate) != "undefined") {
                AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
                ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
                AspValidatorValidate = ValidatorValidate;
                ValidatorValidate = NicerValidatorValidate;
            }
        }
    
        /**
        * This function is called once for each Field Validator, passing in the 
        * Field Validator span, which has helpful properties 'isvalid' (bool) and
        * 'controltovalidate' (string = id of the input field to validate).
        */
        function NicerValidatorUpdateDisplay(val) {
            // Do the default asp.net display of validation errors (remove if you want)
            AspValidatorUpdateDisplay(val);
    
            // Add our custom display of validation errors
            // IF we should be paying any attention to this validator at all
            if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
                if (val.isvalid) {
                    // do whatever you want for invalid controls
                    $('#' + val.controltovalidate).parents('.control-group:first').removeClass('error');
                } else {
                    // reset invalid controls so they display as valid
                    //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                    var t = $('#' + val.controltovalidate).parents('.control-group:first');
                    t.addClass('error');
                }
            }
        }
    
        function NicerValidatorValidate(val, validationGroup, event) {
            AspValidatorValidating = validationGroup;
            AspValidatorValidate(val, validationGroup, event);
        }
    
        // Call UpgradeASPNETValidation after the page has loaded so that it 
        // runs after the standard ASP.NET scripts.
        $(document).ready(UpgradeASPNETValidation);
    
    0 讨论(0)
  • I know this is old, but I have another modified combination from Dillie-O and Alexander. This uses jQuery with the blur event to remove the style when validation succeeds.

    function validateFields() {
        try {
            var count = 0;
            var hasFocus = false;
    
            for (var i = 0; i < Page_Validators.length; i++) {
                var val = Page_Validators[i];
                var ctrl = document.getElementById(val.controltovalidate);
    
                validateField(ctrl, val);
    
                if (!val.isvalid) { count++; }
                if (!val.isvalid && hasFocus === false) {
                    ctrl.focus(); hasFocus = true;
                }
            }
    
            if (count == 0) {
                hasFocus = false;
            }
        }
        catch (err) { }
    }
    
    function validateField(ctrl, val)
    {
        $(ctrl).blur(function () { validateField(ctrl, val); });
    
        if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null
            val.isvalid ? $(ctrl).removeClass("error") : $(ctrl).addClass("error");
        }            
    
        if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox
            var rtxt = document.getElementById(val.controltovalidate + '_text');
            val.isvalid ? $(rtxt).removeClass("error") : $(rtxt).addClass("error");
        }
    }
    
    0 讨论(0)
  • 2020-11-28 07:36

    I made a working one pager example of this for regular asp.net, no .control-group

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html>
    <!-- http://stackoverflow.com/questions/196859/change-text-box-color-using-required-field-validator-no-extender-controls-pleas -->
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
        <script>
            /**
      * Re-assigns the ASP.NET validation JS function to
      * provide a more flexible approach
      */
            function UpgradeASPNETValidation() {
                if (typeof (Page_ClientValidate) != "undefined") {
                    AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
                    ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
                    AspValidatorValidate = ValidatorValidate;
                    ValidatorValidate = NicerValidatorValidate;
                }
            }
    
            /**
            * This function is called once for each Field Validator, passing in the 
            * Field Validator span, which has helpful properties 'isvalid' (bool) and
            * 'controltovalidate' (string = id of the input field to validate).
            */
            function NicerValidatorUpdateDisplay(val) {
                // Do the default asp.net display of validation errors (remove if you want)
                AspValidatorUpdateDisplay(val);
    
                // Add our custom display of validation errors
                // IF we should be paying any attention to this validator at all
                if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
                    if (val.isvalid) {
                        // do whatever you want for invalid controls
                        $('#' + val.controltovalidate).removeClass('error');
                    } else {
                        // reset invalid controls so they display as valid
                        //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                        var t = $('#' + val.controltovalidate);
                        t.addClass('error');
                    }
                }
            }
    
            function NicerValidatorValidate(val, validationGroup, event) {
                AspValidatorValidating = validationGroup;
                AspValidatorValidate(val, validationGroup, event);
            }
    
            // Call UpgradeASPNETValidation after the page has loaded so that it 
            // runs after the standard ASP.NET scripts.
            $(document).ready(UpgradeASPNETValidation);
        </script>
        <style>
            .error {
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    
            <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
            <asp:Button ID="Button1" runat="server" Text="Button" />
    
            <br />
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
            <br />
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="RangeValidator" MaximumValue="100" MinimumValue="0"></asp:RangeValidator>
    
        </div>
        </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 07:36

    Here's some self-contained HTML/JS that does the trick:

    <html>
      <head>
        <script type="text/javascript">
          function mkclr(cntl,clr) {
            document.getElementById(cntl).style.backgroundColor = clr;
          };
        </script>
      </head>
      <body>
        <form>
          <input type="textbox" id="tb1"></input>
          <input type="submit" value="Go"
            onClick="javascript:mkclr('tb1','red');">
          </input>
        </form>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 07:38

    in css:

           .form-control
            {
                width: 100px;
                height: 34px;
                padding: 6px 12px;
                font-size: 14px;
                color: black;
                background-color: white;
            }
            .form-control-Error
            {
                width: 100px;
                height: 34px;
                padding: 6px 12px;
                font-size: 14px;
                color: #EBB8C4;
                background-color: #F9F2F4
                border: 1px solid #DB7791;
                border-radius: 4px;
            }
    

    in your page:

    <asp:TextBox ID="txtUserName" runat="server" CssClass="form-control"></asp:TextBox>
     <asp:RequiredFieldValidatorrunat="server"Display="Dynamic" ErrorMessage="PLease Enter UserName" ControlToValidate="txtUserName"></asp:RequiredFieldValidator>
    

    at the end of your page above of

    <script type="text/javascript">
        function WebForm_OnSubmit() {
            if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
                for (var i in Page_Validators) {
                    try {
                        var control = document.getElementById(Page_Validators[i].controltovalidate);
                        if (!Page_Validators[i].isvalid) {
                            control.className = "form-control-Error";
                        } else {
                            control.className = "form-control";
                        }
                    } catch (e) { }
                }
                return false;
            }
            return true;
        }
    </script>
    
    0 讨论(0)
  • 2020-11-28 07:39

    It is not exactly without changing controls user used to, but I think this way is easier (not writing the full example, I think it is not necessary):

    ASP.NET:

        <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
        <asp:CustomValidator runat="server" ControlToValidate="TextBox1" Display="Dynamic" Text="TextBox1 Not Set" ValidateEmptyText="true" OnServerValidate="ServerValidate" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Execute" />
    

    Code:

    protected void Execute(object sender, EventArgs e)
    {
       Page.Validate();
       if (Page.IsValid)
       {
           *some code*
       }
    }
    
    protected void ServerValidate(object source, ServerValidateEventArgs args)
    {
        CustomValidator cval = source as CustomValidator;
        if (cval == null)
        {
            args.IsValid = false;
            return;
        }
    
        if (string.IsNullOrEmpty(args.Value))
        {
            args.IsValid = false;
            string _target = cval.ControlToValidate;
            TextBox tb = cval.Parent.FindControl(_target) as TextBox;
            tb.BorderColor = System.Drawing.Color.Red;
        }
        else
        {
            args.IsValid = true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题