Asp ajax,设置自定义验证器错误消息

时间:2014-11-05 19:20:12

标签: jquery asp.net ajax webmethod customvalidator

我有自定义验证器

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

我正在对WebMethod进行ajax调用

function validateStuNum(src, args) {
                var numTextbox = document.getElementById('<%=StudentNumTextbox.ClientID%>');
                $.ajax({
                    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;
                    }
                });
            }

       [WebMethod]
    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;
    }

我的问题是我正在尝试从WebMethod中设置验证器文本属性,但是我确定如何去做。根据我发布的内容,我尝试将src发送到方法并将其投射到CustomValidator,但没有运气。我只是希望能够根据输入的错误来获取错误消息。任何帮助表示赞赏

0 个答案:

没有答案