JS:仅在所有输入均通过验证后,才能在表单中启用提交按钮

时间:2019-01-24 01:49:30

标签: javascript

我有一个简单的输入,正在使用keyup事件监听器。如果输入长度太短,则span元素将删除其上隐藏该元素并显示“ Input too short”的类。

如果我有多个输入,那么如果所有字段均通过验证,该如何启用“提交”按钮。
不幸的是,我正在思考,并且会通过状态来实现。

<style type="text/css">
    .hide-first {
        display: none;
    }

    .hide-last {
        display: none;
    }
</style>
<div>
    <div>
        <input id="first-name" />
        <span id="validation-span" class="hide-first">Input too short</span>
    </div>
    <button>Submit</button>
</div>
<script type="text/javascript">
    let firstName = document.getElementById( 'first-name' );
    let span = document.getElementById( 'validation-span' );

    firstName.addEventListener( 'keyup', () => {
        console.log( event.target.value.length )
        if ( event.target.value.length < 5 ) {
            span.classList.remove( 'hide-first' )
        } else {
            span.classList.add( 'hide-first' )
        }
    } );
</script>

4 个答案:

答案 0 :(得分:0)

所有输入都可以调用相同的验证函数,该函数检查除空输入之外的所有内容。仅在所有按钮都成功时才显示提交按钮,并在未通过验证的输入上显示适当的消息。

伪代码:

   boolean succes = true
   if username is invalid and not empty
      username invalid message
      success = false
   if password is invalid and not empty
      password invalid message
      success = false

   if success is true
       show submit button

答案 1 :(得分:0)

简单的逻辑。创建一个检查所有字段是否都经过验证的函数,然后从onkeyup事件中调用它。一种看似简单的方法将是这样的:

let firstName = document.getElementById('first-name'),
    lastName = document.getElementById('last-name'),
    company = document.getElementById('company-name');
let span = document.getElementById('validation-span'),
    span1 = document.getElementById('validation-span1'), 
    span2 = document.getElementById('validation-span2'), 
    conditions = [],
    length = 3;

firstName.addEventListener('keyup', () => {
    console.log(event.target.value.length)
    if (event.target.value.length < 5) {
        span.classList.remove('hide-first')
        conditions[0] = true;
    } else {
        span.classList.add('hide-first')
        conditions[0] = false;
    }
}) 

lastName.addEventListener('keyup', () => {
    console.log(event.target.value.length)
    if (event.target.value.length < 5) {
        span1.classList.remove('hide-first')
        conditions[1] = true;
    } else {
        span1.classList.add('hide-first')
        conditions[1] = false;
    }
})

company.addEventListener('keyup', () => {
    console.log(event.target.value.length)
    if (event.target.value.length < 5) {
        span2.classList.remove('hide-first')
        conditions[2] = true;
    } else {
        span2.classList.add('hide-first')
        conditions[2] = false;
    }
})

function checkAllTrueAndActivateSubmitBtn() {
    var result = true;
    for(var i = 0; i < length; i++) {
        if(!conditions[i]) {
            result = false;
        }
    }
    if(result) {
        submitBtn.classList.add("shown"); //or whatever
    }
}

但是,当然,您拥有的字段越多,混乱就越多。一种更有效的方法是对字段和条件使用数组:

let IDsAndConditions = {
    'first-name':{
        condition: (x) => x.length >= 5,
        span: 'validation-span'
    },
    'last-name': {
        condition: (x) => x.length >= 8,
        span: 'validation-span-lastName'
    },
    'phoneNumber':{
        condition: (x) => x.match(/^-{0,1}\d+$/),//or whatever
        span:"phone-span"
    }
};
var conditions = [];
var num = 0;
for(var k in IDsAndConditions) {
    var cur = IDsAndConditions[k];
    var el = document.getElementById(k);
    var span = document.getElementById(cur["span"]);
    if(el && span) {
        el.addEventListener('keyup', () => {
            console.log(event.target.value.length)
            if (!cur["condition"](event.target.value)) {
                span.classList.remove('hide-first')
                conditions[num] = true;
            } else {
                span.classList.add('hide-first')
                conditions[num] = false;
            }
            checkAllTrueAndActivateSubmitBtn();
        });

    } else {
        conditions[num] = true; //this is to make the validation work even if the element doesn't exist
    }
    num++;
}



function checkAllTrueAndActivateSubmitBtn() {
    var result = true;
    for(var i = 0; i < IDsAndConditions.length; i++) {
        if(!conditions[i]) {
            result = false;
        }
    }
    if(result) {
        submitBtn.classList.add("active"); //or whatever
    } else {
        submitBtn.classList.remove("active"); //even if it was active at one point, if someone changes a field to an incorrect value, it deactivates again
    }
}

答案 2 :(得分:0)

类似的事情应该起作用

<div>
    <div>
        <input id="first-name" onchange='validation()'/>
        <span id ="validation-span" class="hide-first">Input too short</span>
    </div>
    <button id='submit-button'>
        Submit
    </button>
</div>

<script type="text/javascript">
    function validateFirstName() {
        let firstName = document.getElementById('first-name');
        let span = document.getElementById('validation-span');
        if (event.target.value.length < 5) {
            span.classList.remove('hide-first')
            return True
        }
        span.classList.add('hide-first')
        return False
     }

    function validation() {
         let submitButton = document.getElementById('submit-button');
         submitButton.disabled = validateFirstName(); 
    }
</script>

添加其他字段时,应为该字段创建验证功能,然后在validation()内部运行它,如:

function validation() {
    let submitButton = document.getElementById('submit-button');
    submitButton.disabled = validateFirstName() && validateSecondField() && validateThirdField() &&...;
}

请记住将onchange事件监听器添加到html输入中。

答案 3 :(得分:0)

首先添加样式({'weight': 80}, 5) 。您可以将jQuery用作波纹管

style="display:none"