Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net CustomValidator - ClientValidationFunction to check value not blank and not initial value

I have following code which validates the value of a textbox to make sure it's not blank but I also need to check that it does not equal the initial value of the textbox (defaultValue).

Here's what I have so far...

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;
        }
   }

.net

  <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" />
like image 644
Tom Avatar asked Apr 21 '26 00:04

Tom


1 Answers

You can do what you want using a CSS class to identify the TextBox and retrieve it with jQuery, allowing you to obtain the attribute defaultValue:

Markup:

<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" />

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;
     }
 }
like image 84
Marcus Vinicius Avatar answered Apr 22 '26 12:04

Marcus Vinicius