4 Leave Cover
4 Leave Cover

Reputation: 1276

ASP.NET Client-side validation on textbox without postback

I am using ASP.NET and would like to do the following on client side because I do not want the page to reload (do not want postback). I would like to check for user input with following conditions:

  1. There are 2 radiobuttons and 2 textboxes and 1 button. Something like this: enter image description here
  2. User must tick the radiobutton in order to activate the textbox (textboxes by default is disabled)
  3. If user tick radiobutton 1, textbox1 will be activated and textbox2 will be empty and disabled, if user press the button and textbox1 is empty message1 will activate.
  4. Same goes to the second radiobutton and textbox2.

Edit

I noticed that my button is in <asp:button> and not <input type="submit> therefore it will run my code behind to valdiate at server. Correct me if I am wrong. So how do I make my <asp:button> to validate user input without have to pass to server?

Upvotes: 11

Views: 48944

Answers (5)

Phong Vo
Phong Vo

Reputation: 1078

You can try:

<asp:button onClientClick="return validateData();">

And in the JavaScript it should be:

function validateData() {
    if (OK) {
        return true;
    } else {
        return false;
    }
}

return true will make your page be posted back to the server, and return false will prevent your page from doing that. Hope this helps.

Upvotes: 22

Eric
Eric

Reputation: 779

Would adding a validationgroup to your validator as well as the button you where trying to use as the trigger to check for validation?

Validation groups are really easy to use once you get the hang of them. I wont go diving into too many details about validators but if the information would be helpful I can always add it to the post. Hope you had resolved your answer.

Upvotes: 0

Jon P
Jon P

Reputation: 19772

Handling the validation, I would use ASP.net custom validators and use jquery to assis with the client side validation:

ASP.net aspx

<form id="form1" runat="server">
    <div>
        <div id="requiedCheck1" class="check">
           <asp:RadioButton ID="radio1" runat="server" GroupName="myGroup" />
           <asp:TextBox ID="text1" runat="server" Disabled="true"></asp:TextBox>
           <asp:CustomValidator
               ID="val1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text1" ValidateEmptyText="true" ></asp:CustomValidator>
        </div>
        <div id="requiedCheck2" class="check">
           <asp:RadioButton ID="radio2" runat="server" GroupName="myGroup" />
           <asp:TextBox ID="text2" runat="server" Disabled="true"></asp:TextBox>
           <asp:CustomValidator
               ID="CustomValidator1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text2" ValidateEmptyText="true"></asp:CustomValidator>
        </div>
        <asp:button ID="Button1" runat="server" text="Button" />

    </div>
</form>

Note that I have set ValidateEmptyText to true.

js Validation function

function ValidateSomething(sender, args) {

        args.IsValid = false;
        var parentDiv = $(sender).parent(".check");

        var radioChecked = $(parentDiv).find("input:radio").is(":checked");
        var hasText = $(parentDiv).find("input:text").val().length > 0;



        if (radioChecked) {
            args.IsValid = hasText;
        } else {
            args.IsValid = true;
        }

    }

I would also add a server-side validation method too.

If you want to get really fancy you should be able to wire up the radio buttons too. This will fire the validation when the radiobuttons are checked

$(document).ready(function () {

    //Wire up the radio buttons to trigger validation this is optional
    $(".check input:radio").each(function () {
        ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val1.ClientID %>"));
        ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val2.ClientID %>"));
    }); 

    //jquery to change the disabled state
    $(".check :radio").click(function(){
        var parDiv = $(this).parent(".check"); //get parent div
        //empty text and set all to disabled
        $(".check input:text").val("").prop("disabled", true);

        //set target to enabled
        $(parDiv).find("input:text").prop("disabled", false);
     });           
});

I've added the jQuery javascript to toggle the disabled state of the text boxes. You can see the toggle in action here: http://jsfiddle.net/cVACb/

Upvotes: 9

Ajay
Ajay

Reputation: 6590

In your button control, just add the following snippet:

OnClientClick="if(Page_ClientValidate(ValidateSomething)){this.disabled=true;}"

Check this link asp.net Disable Button after Click while maintaining CausesValidation and an OnClick-Method

Upvotes: 0

Mahdi jokar
Mahdi jokar

Reputation: 1267

you should use jquery for your purpose :

<script>
    $(document).ready(function () {
        var Error = false;
        $("#RadioButton1").click(function () {
            $("#TextBox2").attr("disabled", "disabled");
            $("#TextBox1").removeAttr("disabled");
        });
        $("#RadioButton2").click(function () {
            $("#TextBox1").attr("disabled", "disabled");
            $("#TextBox2").removeAttr("disabled");
        });
        $("#Button1").click(function () {
            var TextBox1value = $("#TextBox1").val();
            var TextBox2value = $("#TextBox2").val();
            var TextBox1Disable = $("#TextBox1").attr("disabled");
            var TextBox2Disable = $("#TextBox2").attr("disabled");

            if ((TextBox1value == "") && TextBox1Disable != "disabled") {
                $("#Label1").text("text can not be empty");
                Error = true;
            }
            if ((TextBox2value == "") && TextBox2Disable != "disabled") {
                $("#Label2").text("text can not be empty");
                Error = true;
            }

        });


        $("#form1").submit(function (e) {
            if (Error) {
                alert("there are Some validation error in your page...!");
                e.preventDefault();
            }

        });

    });
</script>

body elements are :

<form id="form1" runat="server">
    <div>
    </div>
    <asp:RadioButton ID="RadioButton1" runat="server" GroupName="g1" /><asp:TextBox ID="TextBox1" runat="server" Enabled="False"></asp:TextBox><asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
    <br />
    <asp:RadioButton ID="RadioButton2" runat="server" GroupName="g1" /><asp:TextBox ID="TextBox2" runat="server" Enabled="False"></asp:TextBox><asp:Label ID="Label2" runat="server" ForeColor="Red"></asp:Label>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" />
</form>

Upvotes: 0

Related Questions