Reputation: 423
i am trying to put asp.net Required Field Validator and Range Validator but only Required Field Validator works not range. why ?
<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" />
Upvotes: 1
Views: 1687
Reputation: 8172
Like DaveParsons mentioned in the comments, I also feel like a RegularExpressionValidator
would be the best approach here.
You can configure it to validate a specific length range as evidenced in this answer.
Upvotes: 0
Reputation: 9621
ASP RangeValidator
is meant to validate that the input is within a given range, whereas in your case it seems you want to validate the input length.
To do this, you can do something like this:
In your page, replace the RangeValidator
by a CustomValidator
:
<asp:CustomValidator runat="server" id="txtCNICValidator"
controltovalidate="txtCNIC" ClientValidationFunction="validateCnic"
errormessage="CNIC must be exactly 15 characters long!" />
And add the corresponding validation function in your javascript:
<script type="text/javascript">
function validateCnic(sender, args) {
args.IsValid = (args.Value.length == 15);
}
</script>
Upvotes: 1