【问题标题】:CustomValidator with js function doesn`t work具有 js 功能的 CustomValidator 不起作用
【发布时间】:2023-03-07 01:19:01
【问题描述】:

我在向导视图中使用 js 函数创建了 CustomValidator,只是为了检查密码长度。 而且他不工作,对不起我的新手。

js函数:

 <script type="text/javascript">
    function clientValidate(sender, args) {
        if (args.Value.length < 5 ||args.Value.length > 30) {
            args.IsValid = false;
        }
    }
</script>

asp 字段:

<asp:TextBox ID="tbPassword1" runat="server" TextMode="Password"></asp:TextBox>
<asp:CustomValidator ID="CustomValidatorPassLength" runat="server" display="Dynamic"     ControlToValidate="tbPassword1" ClientValidationFunction="clientValidate" ErrorMessage="Slaptažodis turi būti nuo 5 iki 30 simbolių ilgio." ForeColor="Red"></asp:CustomValidator>

谢谢,对不起!

【问题讨论】:

  • 文本框为空时是否要触发验证功能?还是根本不起作用?
  • 从空文本框 requiredfield 验证器保护,我想在 tbPassword1.text.length 小于 5 且超过 30 个符号时触发 js 函数。

标签: javascript asp.net customvalidator


【解决方案1】:

仅当用户尝试通过单击按钮等方式提交网络表单时,ASP 自定义验证器才会触发。如果您想在客户端事件期间运行验证,则必须使用 Javascript,而不是 ASP服务器控制。

请参阅此 JS Fiddle Demo,了解您可以做什么的示例。代码如下。

HTML

<input type="text" class="password" id="mytextbox"></input><span class="errormsg">Password length invalid</span>

JQuery / Javascript

$(function(){
    // This is to add the "On Change" event to your textbox.
    $('#mytextbox').change(function(){
        if(!validateFunction($(this))){
            $(this).next('.errormsg').fadeIn({duration: 400});
        } else {
            $(this).next('.errormsg').fadeOut({duration: 100});
        }
    });
})

// This is the function that validates your checkbox. It returns true or false.
function validateFunction(obj){
    if(obj.hasClass('password')){
        var txt = obj.val();
        return (txt.length > 5 && txt.length <= 30);
    }
};

【讨论】:

  • 感谢您的回复! :)
  • @KarolisSemaška 没问题!如果有帮助,请随时将答案标记为正确。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多