JavaScript验证方法未按预期工作



我对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&cURLnone的Javascript验证例程将被使用。本质上不依赖于客户端验证。

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

validation函数实际上只接受用户的date of birth的组成元素进行验证,而忽略了其他字段。通过使用单一的验证功能,您可以尝试确保在验证任务中使用所有表单元素。

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

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-zs]+' 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>

相关内容

  • 没有找到相关文章

最新更新