表单验证需要输入才能继续

时间:2018-01-26 21:44:12

标签: javascript validation

在允许访问者继续前,一旦添加了正确的值,一些简单的表单验证似乎需要点击 Enter 。有什么方法可以消除那种?以下是其中一个例子。

// Makes sure that the email looks valid and contains an @, a . and at least two characters after the dot
function checkEMail(obj) {
    var emailFilter =  /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    if (!emailFilter.test(obj)) {
        obj.style.background = 'Yellow';
        alert('Please enter a valid email address, then press Enter to continue.');
    } else if (!illegalChars.test(obj)) {
        obj.style.background = 'Yellow';
        alert('The email address contains illegal characters.');
    } else {
        obj.style.background = 'White';
    }
}

1 个答案:

答案 0 :(得分:1)

只需在验证功能的“愉快流程”中返回true即可。

// Makes sure that the email looks valid and contains an @, a . and at least two characters after the dot
function checkEMail(obj) {
    var emailFilter =  /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    if (!emailFilter.test(obj)) {
        obj.style.background = 'Yellow';
        alert('Please enter a valid email address, then press Enter to continue.');
    } else if (!illegalChars.test(obj)) {
        obj.style.background = 'Yellow';
        alert('The email address contains illegal characters.');
    } else {
        obj.style.background = 'White';
        return true;
    }
}

具有类似逻辑类型的脚本,工作示例:

function execute(a) {
  if(a === 1) {
    alert("1");
  } else if (a === 2) {
    alert("2");
  } else {
    console.log('lele');
    return true;
  }
}

execute(3);