我正在尝试验证并要求文本框中的电子邮件地址中的字段,但我无法使用RequiredFieldValidator
和RequiredExpressionValidator
,因为它们无法正常工作。< / p>
我有一个脚本,如果用户没有在文本框中输入内容,则需要用户输入一些文本,并且文本框会变为红色,如果用户在此之后输入文本,则会变为绿色。但问题是他变绿了,并且没有显示我的消息,即电子邮件地址的格式无效。
ASP.NET:
<FooterTemplate>
<asp:TextBox ID="txtbemail" runat="server"/>
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtbemail">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate = "txtbemail"
runat="server" ErrorMessage="*Necessário preencher"/>
</asp:RegularExpressionValidator>
<asp:LinkButton ID="LinkButton1" CommandName="AddNew" runat="server" CssClass="btn btn-large btn-info pull-right">
<i class="glyphicon glyphicon-plus"></i> Adicionar
</asp:LinkButton>
</FooterTemplate>
JavaScript:
<script type="text/javascript">
//Define o intervalo para verificar os validadores
setInterval(function () { colorBorders() }, 100);
function colorBorders() {
if (typeof (Page_Validators) !== 'undefined') {
//Faz um loop para verificar os validadores
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
var control = document.getElementById(validator.controltovalidate);
//Verifica se o controle existe
if (control != null) {
// se o validador não for válido, coloque a borda vermelha, se for válida retornar à cor padrão
// elseif com a cor do rgb é necessário para impedir o desdobramento do cromo piscar
if (!validator.isvalid) {
control.style.borderColor = '#ff0000';
} else if (control.style.borderColor == "rgb(255, 0, 0)") {
control.style.borderColor = '#00ff00';
}
}
}
}
}
</script>
问题的屏幕截图:
来自电子邮件的文本框变为绿色但不应该是因为电子邮件的格式不正确。应该变红了。那么,我如何同时要求和验证,并显示所需字段的消息以及无效格式?
答案 0 :(得分:0)
您可以使用ASP.NET验证程序完成此操作。请尝试以下代码段。我已经在我的一个项目中使用它,它可以正常工作。希望它有所帮助。
@Override
protected Map<String,String> getParams()throws AuthFailureError{
Map<String,String> params = new HashMap<String, String>();
Cursor cursor=db.rawQuery(selectQuery,null);
if (cursor.moveToFirst()) {
//iterator integer
int i = 0;
do {
//concatenate the iterator with the name
params.put("code[" + String.valueOf(i) + "]",cursor.getString(2));
params.put("answer[" + String.valueOf(i) + "]", cursor.getString(3));
i++;
} while (cursor.moveToNext());
}
return params;
}
答案 1 :(得分:0)
您可以切换为CustomValidator
并将ValidateEmptyText
设置为true。
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
ClientValidationFunction="checkEmail" ValidateEmptyText="True" SetFocusOnError="true"></asp:CustomValidator>
<script type="text/javascript">
function checkEmail(sender, element) {
//these first 2 lines remove spaces and update the textbox
var emailToCheck = element.Value.replace(/ /g, "");
document.getElementById(sender.controltovalidate).value = emailToCheck;
var filter = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
element.IsValid = filter.test(emailToCheck);
}
</script>