【发布时间】:2011-07-13 01:28:54
【问题描述】:
我有一个表格供用户更改其设置。它有 5 个字段 - 名字、姓氏、密码、确认密码和电子邮件地址。
唯一的事情是我必须确保密码匹配并且电子邮件有效。用户可以使用任何或所有字段。
我想到的可能性是:
- 所有字段中的文本,密码匹配,电子邮件有效 -> 提交
- 只有名字的文本 -> 提交
- 只有姓氏的文字 -> 提交
- 两个名称中的文本 -> 提交
- 仅电子邮件中的文本 -> 提交
- 仅包含电子邮件和名字的文本 -> 提交
- 仅包含电子邮件和姓氏的文本 -> 提交
- 电子邮件中的文本无效 -> 显示无效错误,请勿提交
- 密码字段中的文本不匹配 -> 显示不同的无效错误,请勿提交
我正在使用 jQuery 来处理所有这些。到目前为止,这是我的代码:
$('#success').hide();
$('#pwerror').hide();
$('#subSet').live('click',function() {
//if any of the fields have a value
if($("#chfn").val() != "" || $("#chln").val() != "" || $("#chpw").val() != "" || $("#chpw2").val() != "" || $("#chem").val() != "")
{
//if the email field isn't empty (i.e. something is typed in), then check for email validation and post if valid
if($("#chem").val() != "")
{
$("#profSet").validate({
rules: {
chem: {
email: true
}
}
});
if($("#profSet").valid())
{
$.post('php/profSet.php', $('#profSet').serialize(), function(){
$('#profSet').hide();
$('#success').show();
});
}
}
//checks if either of the password fields are filled
if($("#chpw").val() != "" || $("#chpw2").val() != "")
{
//now checks if they are equal
if($("#chpw").val() == $("#chpw2").val())
{
$.post('php/profSet.php', $('#profSet').serialize(), function(){
$('#profSet').hide();
$('#success').show();
});
}
//if they aren't equal (which means if they are mismatching string, or if either one is blank), show error
else
{
$('#pwerror').show();
}
}
//if it's not an email or password field, then just post, there are no conditionals for the first/last names
if($("").val())
{
$.post('php/profSet.php', $('#profSet').serialize(), function(){
$('#profSet').hide();
$('#success').show();
});
}
}
});
就我如何排序条件而言,这段代码的问题很明显。如果触发了较早的条件,则可能会提交错误的输入并且不检查。
有没有办法在不写出九个不同的 if 语句的情况下使这个表单工作?
【问题讨论】: