如何使用我创建的功能验证表单

时间:2019-06-03 09:39:59

标签: javascript forms validation

我创建了一些函数来验证我的表单。但是当我单击提交按钮时,我希望它们全部一次运行。因此,我有一个formValidate函数,然后有一个firstNameValidate,lastNameValidate等。

我的问题是,我将如何创建formValidate函数来运行我拥有的函数,但是只有在所有函数都正确的情况下才提交表单?

function firstNameValidate() {
    // Making sure that the firstname input is not blank
    if (firstName.value.length == 0) {
        // If the firstname input is blank, then return the error text below
        error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
        // Error text css class
        error.className = 'error';
        // Making sure that the browser window focuses on the error
        firstName.focus();
        // Does not let the browser submit the form
        //  this statement makes sure that the input has only letters
        return false;
    } else if (!firstName.value.match(letter)) {
        // // If the input has something other then numbers, show this error.
        error.innerHTML =
            'Please Enter a Valid First Name, Cannot contain characters(!@#) or numbers';
        // // error text css class
        error.className = 'error';
        // browser window focuses on error
        firstName.focus();
        // Form does not submit
        return false;
    }
    if (firstName.value.length > 0 && firstName.value.match(letter)) {
        error.className = '';
        error.innerHTML = '';
        return true;
    }
}

我可以得到名字和姓氏进行验证,但是如果填写了其中的一个,它将发送表格。因此,我认为返回true和false都是错误的。

2 个答案:

答案 0 :(得分:1)

function firstNameValidate() {

  if (firstName.value.length == 0) {
    error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
    error.className = 'error';
    firstName.focus();
    return false;
  }
  if (!firstName.value.match(letter)) {
    error.innerHTML = 'Please Enter a Valid First Name, Cannot contain characters(!@#) or numbers';
    error.className = 'error';
    firstName.focus();
    return false;
  } else {
    //intended code goes here , or simply return true.
  }

}

如果要进行严格检查,则将所有验证写入if语句中,如果所有内容都正确填充,则在else语句中执行正确的代码,

并在onsubmit表单上调用上面的函数,或单击按钮以完成工作。

希望这会有所帮助.. !!

答案 1 :(得分:-1)

  

但是我希望它们全部都在我单击“提交”按钮时立即运行

您是说要让它们全部并行运行。试试这个,

    function formValidate()
    {
        let promises = [];
        promises.push(new Promise((resolve,reject) ->resolve(firstNameValidator()));
        promises.push(new Promise((resolve,reject) ->resolve(lastNameValidator()));        
        promises.push(new Promise((resolve,reject) ->resolve(otherValidator()));

        Promise.All(promises).then((checks) ->{checks.forEach((check) ->{
                if(!check)return false;}});
        return true;
}

这将立即启动所有检查功能,并在它们全部完成后返回。如果任何一个函数返回false,它将返回false。

如果将显示的错误消息移至检查功能,这将显示所有错误消息。例如

function firstNameValidator()
{
   if(name == null){
        error.innerHTML += 'Please Enter a Valid First Name, Cannot be                       
        Blank';
        error.className = 'error';
        return false;
   }
   return true;
 }