大家好,
我正在编写一个游戏,我有一个步骤,用户可以通过输入多个电子邮件地址将游戏分享给他的朋友。在这一步中,我必须控制每个电子邮件地址的有效性。
我想分解检查电子邮件字段的脚本部分。我的功能有效,但是 if... else if... 的顺序有点奇怪
请你看一下并给我建议。谢谢
HTML
<form id="form-noel" method="post" enctype="multipart/form-data" action="#ok">
<h3>Share the game !</h3>
<p>
<label for="email1">Email 1</label>
<input type="text" id="email1" name="email1" />
<label id="error-email1" class="error"></label>
</p>
<p>
<label for="email2">Email 2</label>
<input type="text" id="email2" name="email2" />
<label id="error-email2" class="error"></label>
</p>
<p>
<label for="email3">Email 3</label>
<input type="text" id="email3" name="email3" />
<label id="error-email3" class="error"></label>
</p>
<p class="textcenter"><input type="submit" id="btn-submit" value="Share" /></p>
</form>
JS
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
function checkEmail(emailVal, named){
if(!isValidEmailAddress(emailVal)){
$('#'+named).addClass('error');
$('#error-'+named).show().attr('title', 'Merci de saisir une adresse email valide (nom@domaine.xxx)');
return false;
}
else {
$('#'+named).removeClass('error');
$('#error-'+named).hide().removeAttr('title');
return true;
}
}
$('#btn-submit').click(function(event){
event.preventDefault();
var email1Val = $('#email1').val();
var email2Val = $('#email2').val();
var email3Val = $('#email3').val();
if(email1Val != '' && email2Val != '' && email3Val != ''){
if(checkEmail(email1Val, 'email1') && checkEmail(email2Val, 'email2') && checkEmail(email3Val, 'email3')){
$('#form-noel').submit();
}
}
else if(email1Val != '' && email2Val != ''){
if(checkEmail(email1Val, 'email1') && checkEmail(email2Val, 'email2')){
$('#form-noel').submit();
}
}
else if(email1Val != '' && email3Val != ''){
if(checkEmail(email1Val, 'email1') && checkEmail(email3Val, 'email3')){
$('#form-noel').submit();
}
}
else if(email2Val != '' && email2Val != ''){
if(checkEmail(email2Val, 'email2') && checkEmail(email3Val, 'email3')){
$('#form-noel').submit();
}
}
else if(email1Val != ''){
if(checkEmail(email1Val, 'email1')){
$('#form-noel').submit();
}
}
else if(email2Val != ''){
if(checkEmail(email2Val, 'email2')){
$('#form-noel').submit();
}
}
else if(email3Val != ''){
if(checkEmail(email3Val, 'email3')){
$('#form-noel').submit();
}
}
else {
$('#form-noel').submit();
}
});