Search code examples
asp.netvalidationclient-side-validation

How do I add custom Javascript to asp.net client side causes validation function?


I have an asp.net web for with a few Validation controls on:

<div class="form-row">
     <label>Email</label>
            <asp:TextBox ID="txtUserName1" runat="server" onchange="validate(this)">    </asp:TextBox>
            <asp:RequiredFieldValidator ID="reqUserName1" runat="server" ControlToValidate="txtUserName1"
                ErrorMessage="- The email address field is required" Text="*" CssClass="error_star" Width="10px" ValidationGroup="Register"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator2" CssClass="error_star" runat="server" ErrorMessage="- Invalid Email Address" Text="*"
                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtUserName1"
                        ValidationGroup="Register"></asp:RegularExpressionValidator> 
        </div>

I have a button to submit the form

<asp:Button ID="cmdSubmit" runat="server" Text="Create Account" CssClass="small-button"
            ValidationGroup="Register" CausesValidation="true" OnClientClick="validateForm()" OnClick="cmdSubmit_Click" />

The first time I hit the button some client side validation is run and my validateForm() method is not hit. for subsequent times I click the submit button my custom validation works fine.

How do I attach some custom JavaScript to the client side validation?

here' the javascript

function validateForm() {
        $("input[type=text], input[type=password]", "#registerForm").each(function () {
            validate(this)
        });
    }

    function validate(control) {
        // Change the colour of the border
        for (var i = 0; i < control.Validators.length; i++) {
            if (!control.Validators[i].isvalid) {
                control.style.border = "1px solid red"
                return;
            }
        }
        control.style.border = "1px solid #E1D7CE"

    }

Solution

  • The page wasn't validating, so the javascript was working but it thought all the controls where valid, I added this

    if (!Page_ClientValidate("Register")) {
                Page_ClientValidate("Register")
            }
    

    to validate the page.