两个字段-交叉验证 [英] Two Fields - Cross Validation

查看:111
本文介绍了两个字段-交叉验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有两个字段,一个是数字值,另一个是日期.

我想要的是验证两个字段都为空或已填充,或者换句话说,如果其中一个字段具有值,则另一个字段也必须具有一个值.逻辑等效为"AND".

有人可以建议通过客户端验证的最佳方法吗?

我确实尝试了两种验证器,但我认为我不能很轻松地在其他领域进行验证,还是有办法解决这个问题?

谢谢!

Hi,

I''ve got two field, one''s a numeric value and the other one is a date.

What I want is to validate that both fields are either empty or filled in or in other words, if either field has a value, the other field also must have a value. The logic equivalent is "AND".

Can anyone suggest the best way to do it via client validation?

I did try custom validators on both but I don''t think I can validate on the other field very easily or is there a way round this?

Thanks!

推荐答案

可以将定制验证器与客户端脚本或服务器代码一起使用.这里我展示了一个客户端验证示例

标记..

Can use Custom validator with client script or with server code. Here I am showing a client side validation example

the markup..

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ValidationGroup="Group1"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"  ClientIDMode="Static"  ValidationGroup="Group1"></asp:TextBox>
<asp:Button ID="Button2" runat="server" ValidationGroup="Group1" Text="Button" />
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" ValidateEmptyText="true" ValidationGroup="Group1" ClientValidationFunction="validate"  runat="server" ErrorMessage="Required Fields Are Blank"></asp:CustomValidator>



我已将clientId模式设置为static以便与javascript一起使用.自定义验证器具有ClientValidationFunction属性.可以将其用于客户端验证.下面是示例脚本,该文本框允许文本框为空或都具有值.如果任何一个都有值,则会引发错误.



I have made the clientId mode to static in order to use ease with javascript. The Custom validator has the ClientValidationFunction attribute. Can use that for validation at client side. Below is the example script to allow text box both blank or both has value. If either one has value it throws error.

<script type="text/javascript" language="javascript">
function validate(source, arguments) {
        text1 = document.getElementById("TextBox1");
        text2 = document.getElementById("TextBox2");
        if ((text1.value == "" || text2.value == "") && !(text1.value == "" && text2.value == "")) {
            arguments.IsValid = false;
        } else {
            arguments.IsValid = true;
        }

    }
</script>


只需快速更新...

我没有使用ASP.NET 4.0,所以无法使用ClientIDMode ="Static".

我必须进行以下更改:
Just a quick update...

I''m not using ASP.NET 4.0 so couldn''t use ClientIDMode="Static".

I had to make the following change:
text1 = document.getElementById("<%=TextBox1.ClientID%>").value;
text2 = document.getElementById("<%=TextBox2.ClientID%>").value;


还可以返回值的一列式(在JavaScript中,空字符串是"falsy")


One-liner for the return value as well (in JavaScript, empty strings are "falsy")

arguments.IsValid = (text1 && text2) || (!text1 && !text2);


这篇关于两个字段-交叉验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆