Search code examples
asp.netcustomvalidator

use custom validator to disable textbox if another is empty


In my project I have to give user option to put a security question and answer to this question, so I have two textboxes one for question and another one for the answer, I want to use ASP.net custom validators to do this task so if question textbox is empty answer textbox will be disabled and when question textbox is not empty answer textbox is enabled.


Solution

  • JavaScript is good enough here:

    <html>
    <head>
    <script type="text/javascript">
    var minimumQuestionLength = 20;
    
    function checkQuestionBox()
      {
        var questionLength=document.getElementById("question").value.length;
    
        if(questionLength < minimumQuestionLength)
        {
           return false;
        }
        return true;
      }
    </script>
    </head>
    <body>
    
    <h1 id="myHeader">Test</h1> 
    <p>Question: <input type="text" id="question"/><br />
    Answer: <input type="text" id="answer" onkeypress="return checkQuestionBox();"/>
    </p>
    
    </body>
    </html>
    

    Fairly simple. You can also disable "answer" on start and then enable once the question is correct, if you prefer that option. Also simple JavaScript.