没有回发的文本框上的ASP.NET客户端验证

时间:2021-07-24 03:41:27

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:

我正在使用ASP.NET,并希望在客户端执行以下操作,因为我不希望页面重新加载(不想要回发)。我想检查以下条件的用户输入:

  1. There are 2 radiobuttons and 2 textboxes and 1 button. Something like this: 没有回发的文本框上的ASP.NET客户端验证
  2. 有2个radiobuttons和2个文本框和1个按钮。像这样的东西:
  3. User must tick the radiobutton in order to activate the textbox (textboxes by default is disabled)
  4. 用户必须勾选单选按钮以激活文本框(默认情况下禁用文本框)
  5. 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.
  6. 如果用户勾选单选按钮1,将激活textbox1并且textbox2将为空并禁用,如果用户按下按钮且textbox1为空,则message1将激活。
  7. Same goes to the second radiobutton and textbox2.
  8. 同样适用于第二个radiobutton和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?

我注意到我的按钮位于 而不是 因此它会将我的代码运行到valdiate at server。如果我错了,请纠正我。那么如何创建我的 验证用户输入而不必传递给服务器? :button> :button>

5 个解决方案

#1


18  

You can try:

你可以试试:

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

And in the JavaScript it should be:

在JavaScript中它应该是:

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.

return true将使您的页面回发到服务器,返回false将阻止您的页面执行此操作。希望这可以帮助。

#2


6  

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

处理验证,我会使用ASP.net自定义验证器并使用jquery来辅助客户端验证:

ASP.net aspx

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.

请注意,我已将ValidateEmptyText设置为true。

js Validation function

js验证功能

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/

我添加了jQuery javascript来切换文本框的禁用状态。您可以在此处看到切换操作:http://jsfiddle.net/cVACb/

#3


0  

you should use jquery for your purpose :

你应该使用jquery为你的目的:

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

#4


0  

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

在保持CausesValidation和OnClick-Method的同时单击后检查此链接asp.net禁用按钮

#5


0  

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.

一旦掌握了它们,验证组就非常容易使用。我不会深入了解有关验证器的太多细节,但如果信息有用,我可以随时将其添加到帖子中。希望你已经解决了你的答案。

#1


18  

You can try:

你可以试试:

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

And in the JavaScript it should be:

在JavaScript中它应该是:

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.

return true将使您的页面回发到服务器,返回false将阻止您的页面执行此操作。希望这可以帮助。

#2


6  

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

处理验证,我会使用ASP.net自定义验证器并使用jquery来辅助客户端验证:

ASP.net aspx

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.

请注意,我已将ValidateEmptyText设置为true。

js Validation function

js验证功能

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/

我添加了jQuery javascript来切换文本框的禁用状态。您可以在此处看到切换操作:http://jsfiddle.net/cVACb/

#3


0  

you should use jquery for your purpose :

你应该使用jquery为你的目的:

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

#4


0  

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

在保持CausesValidation和OnClick-Method的同时单击后检查此链接asp.net禁用按钮

#5


0  

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.

一旦掌握了它们,验证组就非常容易使用。我不会深入了解有关验证器的太多细节,但如果信息有用,我可以随时将其添加到帖子中。希望你已经解决了你的答案。