[英]Prevent Range Validator to show error message with regular expression validator in asp.net
[英]Customise error message on asp.net range validator
您好,是否可以根據文本框的值更改 asp.net 范圍驗證器的錯誤消息。 例如,如果數字小於 0,則顯示錯誤消息“數字不能小於 0”,如果數字大於最大值,則將錯誤消息設置為“數字不能大於最大值”。
if (stockCount < Convert.ToInt32(range.MinimumValue))
{
range.ErrorMessage = "Quantity has to be minumm of 1";
}
else if (stockCount > Convert.ToInt32(range.MaximumValue))
{
range.ErrorMessage = "Not enough items in stock";
}
這是我沒有成功的代碼,非常感謝任何建議或建議。
您可以在 TextBox 上使用一個簡單的 jQuery 偵聽器,並根據它的輸入更改錯誤消息。
<script type="text/javascript">
$('#<%= TextBox1.ClientID %>').keyup(function () {
var validator = document.getElementById('<%= RangeValidator1.ClientID %>');
var errorMsg = 'Your value of ' + $(this).val() + ' is incorrect (max is ' + validator.maximumvalue + ')';
$('#<%= RangeValidator1.ClientID %>').text(errorMsg);
});
</script>
如果您只想在 ASP.NET 和 C# 中嘗試以下操作:
為您的文本框聲明一個rangevalidator
器
<asp:TextBox id="text1" runat="server"></asp:TextBox><br />
<asp:RangeValidator EnableClientScript="false"
id="RangeValidator1"
runat="server"
ControlToValidate="text1" >
</asp:RangeValidator>
您必須調用RangeValidator
的Validate()
函數。 在你的代碼中,在你想要驗證的地方嘗試下面的偽代碼。 (未測試)
RangeValidator1.MinimumValue = 0;
RangeValidator1.MaximumValue = 10;
RangeValidator1.Type = ValidationDataType.Integer;
RangeValidator1.Validate();
if (!RangeValidator1.IsValid)
{
if(Convert.ToInt32(text1.Text) < 0)
{
RangeValidator1.ErrorMessage = "number can not be less than 0";
}
else
{
RangeValidator1.ErrorMessage = "number can't be above maxvalue";
}
}
也許我的回答沒有顯示兩條不同的消息,但我認為將消息總結在一條錯誤消息中更簡單、更清晰。 您可以使用 Class 並將帶有錯誤消息的 Range 驗證器放在頂部。
如果我的建議不合您的口味,我深表歉意。
public class Example
{
[Range(10, 1000, ErrorMessage = "Value must be between {1} and {2}.")]
public int Quantity { get; set; }
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.