ASP.net CustomValidator - ClientValidationFunction,用于检查值不是空白而不是初始值

Tom*_*Tom 3 javascript asp.net validation

我有以下代码验证文本框的值,以确保它不是空白但我还需要检查它是否不等于文本框的初始值(defaultValue).

这是我到目前为止所拥有的......

使用Javascript:

function textValidation(source, arguments)
   {
        if ( arguments.Value != "" ){ // && arguments.Value != arguments.defaultValue
            arguments.IsValid = true;
        } else {
            $(source).parents("div").css({"background-color":"red"});
            arguments.IsValid = false;
        }
   }
Run Code Online (Sandbox Code Playgroud)

.净

  <asp:TextBox runat="server" ID="Initial" Text="Initial" defaultValue="Initial" Width="120px" />                               

<asp:CustomValidator id="Initial_req"
     ControlToValidate="Initial"
     ClientValidationFunction="textValidation"
     ValidateEmptyText="true"
     runat="server"
     CssClass="errorAsterisk"
     Text="*" 
     ErrorMessage="Complete all correspondence fields" />
Run Code Online (Sandbox Code Playgroud)

Mar*_*ius 10

您可以使用CSS类来执行您想要的操作,以识别TextBox并使用jQuery检索它,从而可以获取属性defaultValue:

标记:

<asp:TextBox runat="server" 
             ID="Initial" 
             Text="Initial" 
             defaultValue="Initial" 
             Width="120px" 
             ValidationGroup="Test" 
             CssClass="to-validate" />

<asp:CustomValidator ID="Initial_req" 
   ControlToValidate="Initial" 
   ClientValidationFunction="textValidation"
   ValidateEmptyText="true" 
   runat="server" 
   CssClass="errorAsterisk" 
   Text="*" 
   ErrorMessage="Complete all correspondence fields"
   ValidationGroup="Test" />

<asp:Button ID="btnValidate" runat="server" Text="Validate" ValidationGroup="Test" />
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

function textValidation(source, arguments) {
     var initialValue = $(source).siblings(".to-validate:first").attr("defaultValue");

     if (arguments.Value != "" && arguments.Value != initialValue) { // && arguments.Value != arguments.defaultValue
         arguments.IsValid = true;
     } else {
         $(source).parents("div").css({ "background-color": "red" });
         arguments.IsValid = false;
     }
 }
Run Code Online (Sandbox Code Playgroud)