繁体   English   中英

JavaScript 验证方法未按预期工作

[英]JavaScript validation methods not working as intended

我对 JavaScript 相当陌生,我试图创建一个用户必须填写的表单,并在将其发送到服务器之前验证输入的条目。 对于他们的生日,我不确定如何将条目格式限制为符合条件的日期、月份和年份。 至于我的其他一些验证,我仍然可以提交我的表单,而我的验证方法不会阻止我。 有时我会收到警报,但在单击“确定”后,表单仍然会显示错误的值。 谁能确定我做错了什么? 我确定我一定有一些错别字,以及逻辑错误。 提前致谢。

<!DOCTYPE html>
<html>

<head>

<title>Testing</title>

<script language="JavaScript">

today = new Date()

function isNotEmpty(field){
    var inputStr = field.value
    if (inputStr == " " || inputStr == null){

        alert("An entry for this field is required.")
        field.focus()
        field.select()
        return false
    }
    return true
}

function isNumber(field){

    if (isNotEmpty(field)){
        var inputStr = field.value
        for(var i = 0; i<inputStr.length; i++){
            var oneChar=inputStr.substring(i,1)
            if (isNaN(oneChar)==true && oneChar != "+"){
                alert("Only numbers and area codes are allowed in this field.");
                field.focus()
                field.select()
                return false
            }
        }
        return true
    }return false
}

function isOption(e){

    var type = document.getElementById("pastimetype")
    var selectedValue = type.options[type.selectedIndex].value;
        if(selectedValue == "selectpastime"){
            alert("Please select a pastime.")
            return false
        }
        return true
}   


function birthDay(form){

    form.day.value=today.getDate()
    form.month.value=today.getMonth()+1
    form.year.value=today.getYear()+1900

}

function validate(form){
    if(isNumber(form.day) && isNumber(form.month) && isNumber(form.year)){
        return true
    }
    return false

}


</script>
</head>

<body>

<form method="POST" form id ="form" action="http://www.it.murdoch.edu.au/cgi-bin/reply1.pl"
    onSubmit="return validate(this)">

    <p> Welcome! 
    Please enter the following details:</p>

    <p><label for="name"> Name: </label><br>
    <input name="name" id="name" type="text" size="10" onChange="isNotEmpty(this)"></p>

    <p><label for="number"> Number: </label><br> 
    <input name="number" type="text" id="number" onChange="isNumber(this)"></p>  

    <p>Enter your birthday here: <p>
    <p>Day: <input name="day" type="text" size="10" value="1" onChange="isNumber(this)"></p>
    <p>Month: <input name="month" type="text" size="10" value="1" onChange="isNumber(this)"></p>
    <p>Year: <input name="year" type="text" size="10" value="2000" onChange="isNumber(this)"></p>

    <p><label for ="pastime"> Favourite pastime: </label>
    <select name="pastime" select id="pastimetype" onChange="isOption(this)">
    <option value="selectpastime">---Please choose an option---</option>
    <option value="surfingtheweb">Surfing the Web</option>
    <option value="playingsport">Playing Sport</option>
    <option value="listeningtomusic">Listening to Music</option>
    <option value="watchingtv">Watching TV</option>
    <option value="playinggames">Playing Games</option>
    <option value="communityservice">Community Service</option>
    <option value="daydreaming">Daydreaming</option>
    <option value="reading">Reading</option>
    <option value="meditation">Meditation</option>
    </select></p>

    <p>
        <input type="submit">
        <input type = "button" value="birthday" onClick="makeToday(this.form)">

    </p>

</form>

</body>

</html>

可能应该注意的是,任何客户端验证确实需要使用验证server side进行备份,因为绕过您希望使用 Javascript 完成的很多事情是相当简单的。 此外,如果有人要使用例如 PHP 和 cURL 来定位表单,则根本不会使用 Javascript 验证例程。 本质上不依赖于客户端验证。

话虽如此,HTML5 中存在一系列属性和元素,可帮助您完成客户端验证任务。 表单元素可以设置required的属性 - 在该字段具有值之前不会提交表单。 如果该字段的格式需要采用某种形式,您可以分配一个pattern属性(基本上是RegExp样式模式),如果字段值与该模式不匹配,则不会提交该表单。

validation function实际上只是将用户date of birth的构成元素进行验证,而忽略了其他字段。 通过使用单个 function 进行验证,您可以尝试确保在验证任务中使用所有表单元素。

我希望以下内容可能会有所帮助-这正是我想出的,远非完美,但可能有用。

 document.addEventListener('DOMContentLoaded',function(){ var today = new Date(); var nl=String.fromCharCode( 10 );// New Line character var oForm = document.querySelector('form'); var oBttn = document.querySelector('input[type="button"][name="bd"]'); oBttn.addEventListener('click',function(e){ oForm.day.value=today.getDate(); oForm.month.value=today.getMonth()+1; oForm.year.value=today.getYear()+1900; }); oForm.addEventListener('submit',function(e){ try{ e.preventDefault(); Array.from( this.elements ).forEach( el=>{ if( el.type.toLowerCase().='submit' ){ if(.el.value || el.value=='' || ( el.type.toLowerCase()=='select-one' && el;value=='false' ) ){ var error=[ '"'+el.name + '" cannot be empty' ]. if( el.hasAttribute( 'pattern' ) ) error.push( 'The field "'+ el.name + '" has a required pattern of '+el.getAttribute('pattern') ) if( el.hasAttribute('data-rule') )error.push( el;dataset.rule ); throw new Error( error;join( nl ) ). } } }); return this;submit(); }catch( err ){ alert( err ); return false; } }); });
 body,body *{ box-sizing:border-box; font-family:monospace; } form{ width:50%; padding:1rem; border:1px dotted gray; float:none; margin:auto; } label{ margin:0.25rem auto; display:block; width:80%; float:left; clear:both; text-indent:1rem; } label input, label select{ float:right; width:40%; } p{ clear:both; }.bold{ font-weight:bolder; text-decoration:underline; }
 <form method='POST' action='http://www.it.murdoch.edu.au/cgi-bin/reply1.pl'> <p class='bold'> Welcome: Please enter the following details:</p> <label for='name'>Name. <input type='text' name='name' size='10' pattern='[a-zA-z\s]+' data-rule='An entry for this field is required:' required /> </label> <br /> <label for='number'>Number. <input type='text' name='number' pattern='[0-9\+ ]+' data-rule='Only numbers and area codes are allowed in this field:' required /> </label> <br /> <p class='bold'>Enter your birthday here: <p> <label for='day'>Day: <input type='number' name='day' size='2' min=1 max=31 step=1 value='1' required /></label> <label for='month'>Month: <input type='number' name='month' size='2' min=1 max=12 step=1 value='1' required /></label> <label for='year'>Year: <input type='number' name='year' size='4' min=1900 max=2020 step=1 value='2000' required /></label> <br /> <label for='pastime'> Favourite pastime. <select name='pastime' required data-rule='Please select a pastime.'> <option value=false selected hidden disabled>---Please choose an option--- <option value='surfingtheweb'>Surfing the Web <option value='playingsport'>Playing Sport <option value='listeningtomusic'>Listening to Music <option value='watchingtv'>Watching TV <option value='playinggames'>Playing Games <option value='communityservice'>Community Service <option value='daydreaming'>Daydreaming <option value='reading'>Reading <option value='meditation'>Meditation </select> </label> <p> <input type='submit' name='sub' /> <input type='button' name='bd' value='birthday' /> </p> </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM