I have a custom validator

<asp:CustomValidator runat="server" ValidateEmptyText="True" ClientValidationFunction="validateStuNum" ControlToValidate="StudentNumTextbox" ID="studentnumValidator" OnServerValidate="ValidateStudentNum" ForeColor="#790000" Display="Dynamic" />

And I'm making an ajax call to a WebMethod

function validateStuNum(src, args) {
                var numTextbox = document.getElementById('<%=StudentNumTextbox.ClientID%>');
                    type: "POST",
                    url: "Default.aspx/ValidateAjaxStudentNum",
                    data: JSON.stringify({ 'stuNum': numTextbox.value, 'sender':src }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (valid) {
                        if (!valid.d) {
                            document.getElementById('<%=studentNum.ClientID%>').style.backgroundColor = "#FFDFE0";
                        args.IsValid = valid.d;

    public static bool ValidateAjaxStudentNum(string stuNum, object sender)
        CustomValidator valid = (CustomValidator) sender;

        const string strRegex = @"\d{9}";
        Regex regex = new Regex(strRegex);
        if (stuNum.Equals(string.Empty))
            valid.Text = "This field is required";
            throw new Exception();
        if (!regex.IsMatch(stuNum))
            valid.Text = "Invalid Student number format";
            return false;
        return true;

My problem is that I'm trying to set the validators text property from inside the WebMethod, however I'm sure how to go about doing that. From what I posted, I tried sending src to the method and casting it to a CustomValidator with no luck. I just want to be able to have error messages based on what is wrong with the input. Any help is appreciated

Related posts

Recent Viewed