开发者

asp:textbox validation for integers and zero alone

I'm working on asp.net website. I have asp:texbox. I need validate the text box at clientside using javascript.

I want to prevent the user from entering the values other than intergers and aslo from enter开发者_JS百科ing 0(zero) alone. I mean he should not enter only 0. How can I achieve pls help me. and I just want to prevent the user and don't want to show error message.


Using purely ASP.NET, this is what you're looking for:

<asp:TextBox runat="server" ID="myTb" />
<asp:CompareValidator runat="server" ID="cmp1" Operator="DataTypeCheck" Type="Integer" ControlToValidate="myTb" EnableClientScript="true" ErrorMessage="A numeric value is required." />
<asp:RequiredFieldValidator runat="server" ID="rfv1" InitialValue="0" ControlToValidate="myTb" EnableClientScript="true" Text="*" ErrorMessage="A value is required." />

Very important to understand that using ASP.NET here isn't going to ignore non-numeric keystrokes. It's going to prevent the user from submitting the form with non-numeric values in myTb, and it will stop myTb from submitting with its default value of 0.

UPDATE: Here's an alternative using a custom validator that will allow you to enable the submit button on change when the textbox's text is valid - remember, this is onchange, not onkeydown/up, so the user must change focus (tab off of the textbox) before the validator will fire. I'd recommend going with solution 1 if you're just starting out and not very comfortable with javascript:

<script type="text/javascript">
function mytb_customValidate(sender, args) {
    if (isNaN(args.Value)) {
        args.IsValid = false;
    } else if (args.Value == 0) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
    $get("btn1").disabled = args.IsValid ? "" : "disabled";
}
</script>

<asp:TextBox runat="server" ID="myTb" /> 
<asp:CustomValidator runat="server" ID="cstv1" ClientValidationFunction="mytb_customValidate" EnableClientScript="true" ControlToValidate="myTb" ValidateEmptyText="true" Text="*" ErrorMessage="A non-zero numeric value is required." />
<asp:Button runat="server" ID="btn1" Text="Click Me!" Enabled="false"/>

One last quick update - to accomplish your goal of not showing any errors w/ the validation, simply remove the ErrorMessage= and Text= attributes from the asp:CustomValidator above...

Happy coding!

B

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜