我添加了一个CustomValidator ClientValidationFunction来验证我的Web应用程序中的文本字段,但是,此验证功能根本不会触发。 这是我的验证功能:
function isValidYear(sender,args)
{
alert('Me here');
var year = document.getElementById('MainContent_frmArticle_Source_txtYear').value;
var currentdate = new Date();
var regex = new RegExp("^\d{4}$");
if (year > 1 && year <= currentdate.getFullYear() && regex.test(year)) {
alert('IsValid');
args.IsValid = true;
}
else
{
alert('Is Not Valid');
args.IsValid = false;
}
//我添加了这些警报只是为了测试函数是否被触发,但它们从未显示过。
这是我的自定义验证码:
<asp:TextBox ID="txtYear" runat="server" widtth="20%"></asp:TextBox>
<asp:CustomValidator runat="server" ID="CustomValidateYear" ClientValidationFunction="isValidYear" ControlToValidate="txtYear" ErrorMessage="Please enter a valid year" Display="Static" ForeColor="Red" ></asp:CustomValidator>
更多信息:
我正在使用Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.6.114.0并且在添加验证器后的第一次运行中我收到了“不显眼的验证”的错误,所以我按照网站上的步骤(我不记得它是哪一个)将软件包安装到我的项目:
<package id="AspNet.ScriptManager.jQuery" version="2.1.4" targetFramework="net45" />
<package id="jQuery" version="2.1.4" targetFramework="net45" />
<package id="Microsoft.AspNet.ScriptManager.MSAjax" version="5.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.ScriptManager.WebForms" version="5.0.0" targetFramework="net45" />
请注意,我不想像SO上的大多数帖子所提到的那样将不显眼的验证设置为无。
答案 0 :(得分:2)
Code you posted works, only what I noticed that you missed closing bracket } in your js function isValidYear, and check if you put it inside <script type="text/javascript"></script>
so it will look like
<script type="text/javascript">
function isValidYear(sender, args) {
alert('Me here');
var year = document.getElementById('MainContent_frmArticle_Source_txtYear').value;
var currentdate = new Date();
var regex = new RegExp("^\d{4}$");
if (year > 1 && year <= currentdate.getFullYear() && regex.test(year)) {
alert('IsValid');
args.IsValid = true;
}
else {
alert('Is Not Valid');
args.IsValid = false;
}
}
</script>
Also please notice CustomValidator won't fire on empty text you need to add RequiredFieldValidator
btw you can simply replace yours document.getElementById('MainContent_frmArticle_Source_txtYear').value
with
args.Value