我正在尝试将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" />
答案 0 :(得分:1)
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>
答案 1 :(得分:0)
与评论中提到的DaveParsons一样,我也觉得RegularExpressionValidator
会是最好的方法。
您可以将其配置为验证特定长度范围,如this answer中所示。