表单验证javascript-检查输入值

表单验证javascript-检查输入值,javascript,validation,Javascript,Validation,我试图对每个输入值使用相同的函数来验证表单中的所有输入。 如果输入不为空,则应提交表单。 函数validateInputs()仅当输入不为空时才应返回true,但始终以某种方式返回true,因此表单将随空输入一起提交 //Html code <div class="entry-form"> <form id="form"> <div class="form-control

我试图对每个输入值使用相同的函数来验证表单中的所有输入。 如果输入不为空,则应提交表单。 函数validateInputs()仅当输入不为空时才应返回true,但始终以某种方式返回true,因此表单将随空输入一起提交

//Html code
<div class="entry-form">
          <form id="form">

            <div class="form-control">
                <label for="firstName">First name</label>
                <input type="text" name="First name" id="firstName" />
                <small>Error Message</small>
            </div>

            <div class="form-control">
                <label for="otherNames">Other names</label>
                <input type="text" name="Other names" id="otherNames" />
                <small>Error Message</small>
            </div>

            <div class="form-control">
                <label for="emailAddress">Email address</label>
                <input type="text" name="Email address" id="emailAddress" onfocusout="validateEmail()"/>
                <small>Error Message</small>
            </div>

            <div class="form-control">
                <label for="contact-num">Phone number</label>
                <input type="text" name="Phone number" id="contact-num" onfocusout="validatePhone()" />
                <small>Error Message</small>
            </div>
            
            <div class="form-control">
                <label for="street">Street</label>
                <input type="text" name="Street" id="street" />
                <small>Error Message</small>
            </div>

            <div class="form-control">
                <label for="town">Town</label>
                <input type="text" name="Town" id="town" />
                <small>Error Message</small>
            </div>

            <div class="form-control">
                <label for="country">Country</label>
                <input type="text" name="Country" id="country" />
                <small>Error Message</small>
            </div>
          </form>


 addBtn.addEventListener("click", function () {
    if (
        validateInputs([firstName, otherNames, street, town, country]) &&
        validateEmail() &&
        validatePhone()
    ) {
        id++;
        //creating a new contact object
        const contact = new Contact(id, firstName.value, otherNames.value, emailAddress.value, number.value, street.value, town.value, country.value);

        //push to the array
        ContactArray.push(contact);

        //Storing contact record in local storage
        localStorage.setItem("contacts", JSON.stringify(ContactArray));

        //Clear input fields after submit
        clearInputFields();
        //Adding to list
        addToList(contact);
        //success message
        setMessage();
    }
});

const validateInputs = (inputArr) => {
    inputArr.forEach(input => {
        // check if is empty
        if (checkIfEmpty(input)) return;
        if (!checkIfOnlyLetters(input)) return;
        return true
    })
}


function checkIfEmpty(field) {
    console.log(field.name)
    if (isEmpty(field.value.trim())) {
        // set field invalid
        setInvalid(field, `${field.name} must not be empty`);
        return true;
    } else {
        // set field valid
        setValid(field);
        return false;
    }
}

function isEmpty(value) {
    if (value === '') return true;
    return false;
}
function setInvalid(field, message) {
    field.className = 'invalid';
    field.nextElementSibling.innerHTML = message;
    field.nextElementSibling.style.color = error;
    field.nextElementSibling.style.display = "block";
}
function setValid(field) {
    field.className = 'valid';
    field.nextElementSibling.innerHTML = '';
    //field.nextElementSibling.style.color = green;
}
function clearAll(fields) {
    fields.forEach(function (field) {
        // check if is empty
        field.className = "clear";
        field.nextElementSibling.innerHTML = '';
    })

}

//check if contains only letters
function checkIfOnlyLetters(field) {
    if (/^[a-zA-Z ]+$/.test(field.value)) {
        setValid(field);
        return true;
    } else {
        setInvalid(field, `${field.name} must contain only letters`);
        return false;
    }
}


//Html代码
名字
错误消息
其他名称
错误消息
电子邮件地址
错误消息
电话号码
错误消息
街头
错误消息
城镇
错误消息
国家
错误消息
addBtn.addEventListener(“单击”,函数(){
如果(
验证输入([名字、其他名字、街道、城镇、国家])&&
validateEmail()&&
电话
) {
id++;
//创建新的联系人对象
const contact=新联系人(id、firstName.value、otherNames.value、emailAddress.value、number.value、street.value、town.value、country.value);
//推到阵列上
触点阵列。按下(触点);
//在本地存储器中存储联系人记录
setItem(“contacts”,JSON.stringify(ContactArray));
//提交后清除输入字段
clearInputFields();
//添加到列表中
地址列表(联系人);
//成功信息
setMessage();
}
});
常量validateInputs=(inputArr)=>{
inputArr.forEach(输入=>{
//检查是否为空
if(checkIfEmpty(输入))返回;
如果(!checkIfOnlyLetters(输入))返回;
返回真值
})
}
函数checkIfEmpty(字段){
console.log(field.name)
if(isEmpty(field.value.trim())){
//设置字段无效
setInvalid(字段,${field.name}不能为空);
返回true;
}否则{
//将字段设置为有效
setValid(字段);
返回false;
}
}
函数isEmpty(值){
如果(值=='')返回true;
返回false;
}
函数集无效(字段、消息){
field.className='无效';
field.nextElementSibling.innerHTML=消息;
field.nextElementSibling.style.color=错误;
field.nextElementSibling.style.display=“block”;
}
函数setValid(字段){
field.className='valid';
field.nextElementSibling.innerHTML='';
//field.nextElementSibling.style.color=绿色;
}
函数clearAll(字段){
fields.forEach(函数(字段){
//检查是否为空
field.className=“清除”;
field.nextElementSibling.innerHTML='';
})
}
//检查是否只包含字母
函数检查onlytters(字段){
如果(/^[a-zA-Z]+$/.test(field.value)){
setValid(字段);
返回true;
}否则{
setInvalid(字段,${field.name}只能包含字母`);
返回false;
}
}

我认为您的问题在于
验证输入功能:

const validateInputs=(inputArr)=>{
inputArr.forEach(输入=>{
//检查是否为空
if(checkIfEmpty(输入))返回;
如果(!checkIfOnlyLetters(输入))返回;
返回真值
})
}
它有两个问题:

  • 函数不返回任何值,尽管它在if语句中使用
  • forEach方法也不返回任何内容-。它用于以函数语法(类似于for…of循环)迭代数组
  • 如果您的目标是函数“仅当输入不为空时才返回true”,则需要检查每个输入的条件,并对所有输入运行“&&”。我所知道的对输入数组执行此操作的最佳方法是

    在您的情况下,我将按照以下方式重写函数:

    const validateInputs=(inputArr)=>
    inputArr.every(输入=>!checkIfEmpty(输入)和&checkifonlylters(输入));
    
    请注意,通过从函数中删除大括号(“{”和“}”),我将使用arrow函数语法直接返回它的值(我认为这是您的意图)

    const validateInputs=(inputArr)=>{
    返回inputArr.every(输入=>!checkIfEmpty(输入)和&checkifonlylters(输入));
    }
    
    我认为您的问题在于
    验证输入功能:

    const validateInputs=(inputArr)=>{
    inputArr.forEach(输入=>{
    //检查是否为空
    if(checkIfEmpty(输入))返回;
    如果(!checkIfOnlyLetters(输入))返回;
    返回真值
    })
    }
    
    它有两个问题:

  • 函数不返回任何值,尽管它在if语句中使用
  • forEach方法也不返回任何东西-。它用于以函数语法(类似于for…of循环)在数组上迭代
  • 如果您的目标是函数“仅当输入不为空时才返回true”,则需要检查每个输入的条件,并对所有输入运行“&&”。我所知道的对输入数组执行此操作的最佳方法是

    在您的情况下,我将按照以下方式重写函数:

    const validateInputs=(inputArr)=>
    inputArr.every(输入=>!checkIfEmpty(输入)和&checkifonlylters(输入));
    
    请注意,通过从函数中删除大括号(“{”和“}”),我将使用arrow函数语法直接返回它的值(我认为这是您的意图)

    const validateInputs=(inputArr)=>{
    返回i
    
    const validateInputs = (inputArr) => {
        return inputArr.every(input => {
            // check if is empty
            if (checkIfEmpty(input)) return false;
            if (!checkIfOnlyLetters(input)) return false;
            return true;
        })
    }