范围验证器不工作
本文关键字:工作 验证 范围 | 更新日期: 2023-09-27 18:03:45
我试图把asp.net必填字段验证器和范围验证器,但只有必填字段验证器工作不范围。为什么?
<asp:TextBox ID="txtCNIC" runat="server" CssClass="textField_width"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtCNIC" ErrorMessage="RequiredFieldValidator" ForeColor="#FF3300" SetFocusOnError="True" ValidationGroup="Complaints">CNIC is Required</asp:RequiredFieldValidator>
<asp:RangeValidator
ControlToValidate="txtCNIC"
MinimumValue="14"
MaximumValue="16"
Type="String"
ValidationGroup="Complaints"
EnableClientScript="false"
Text="CNIC can not be longer than 15 characters"
runat="server" />
<asp:Button ID="btnSave" CssClass="btn btn-success" runat="server" Text="Save"
ValidationGroup="Complaints" ClientIDMode="Static" OnClick="btnSave_Click" />
ASP RangeValidator
旨在验证输入在给定范围内,而在您的情况下,似乎您想验证输入长度。要做到这一点,您可以这样做:
在您的页面中,将RangeValidator
替换为CustomValidator
:
<asp:CustomValidator runat="server" id="txtCNICValidator"
controltovalidate="txtCNIC" ClientValidationFunction="validateCnic"
errormessage="CNIC must be exactly 15 characters long!" />
并在javascript中添加相应的验证函数:
<script type="text/javascript">
function validateCnic(sender, args) {
args.IsValid = (args.Value.length == 15);
}
</script>
就像DaveParsons在评论中提到的那样,我也觉得RegularExpressionValidator
将是这里最好的方法。
您可以配置它来验证这个答案中所证明的特定长度范围。