JavaScript表单验证 -

时间:2015-08-14 05:04:54

标签: javascript html

我正在尝试获得基本的javascript验证。出于某种原因,它正在拾取文本和下拉但不是单选按钮?我究竟做错了什么?

JS Fiddle

<script>
    function validateForm(formId)
    {
        var inputs, index;
        var form=document.getElementById(formId);
        inputs = form.getElementsByTagName('input');
        for (index = 0; index < inputs.length; ++index) {
            // deal with inputs[index] element.
            if (inputs[index].value==null || inputs[index].value==""))
                {
                    alert("Field is empty");
                    return false;
                 }
     }
</script> 

2 个答案:

答案 0 :(得分:1)

要验证单选按钮,您需要浏览所有广播,并查看哪个checked属性为true

<script>
      function validateForm(){
            for(i=0; i<document.form.radios.length; i++){       
              if(document.form.radios[i].checked==false){
              c=1;
              }
                else{
                c=0;
                break;
                }}        

                if(c==1){
                alert('Please select an option');
                }
         }
 </script>
  

document.form.radios.length给出了单选按钮的数量。

您还可以使用HTML的required属性来实现相同的功能。

<form>
      <input type="radio" name="gender" value="Male" required /> Male
      <input type="radio" name="gender" value="Female" /> Female

      <input type="submit" name = "sub" value="SAVE" />
</form>

Fiddle

答案 1 :(得分:1)

下面提供了一种方法,可以识别表单中是否有多个单选按钮

function hasEmptyRadio(radioMap) {
    var emptyRadio = false;
    for (var i in radioMap) {
        if (radioMap.hasOwnProperty(i) && !radioMap[i]) {
            emptyRadio = true;
            break;
        }
    }
    return emptyRadio; // return the radio object or name if required
}

function markEmptyRadios(radioMap, radioObj) {
    var checked = radioObj.checked;
    radioMap[radioObj.name] = radioMap[radioObj.name] || checked;
}


function validateForm(formId) {
    var inputs, index;
    var radioMap = {};
    var form = document.getElementById(formId);
    inputs = form.getElementsByTagName('input');
    for (index = 0; index < inputs.length; ++index) {
        if (inputs[index].type === 'radio') {
            markEmptyRadios(radioMap, inputs[index])
        }
        // Your check for other input type can go here
    }
    alert("Radio Empty check returned => " + hasEmptyRadio(radioMap));
}