简体   繁体   中英

JavaScript validation methods not working as intended

I'm fairly new to JavaScript and im trying to create a form that a user has to fill, and validate the entries put it before it is sent off to a server. For their birthday, I'm unsure how to limit the entry format to eligible days, months and years. As for some of my other validations, I'm still able to submit my form without my validation methods stopping me. Sometimes I get the alerts, but after clicking 'OK' the form still goes through with the wrong values. Can anyone identify what I'm doing wrong? I'm sure I must be having some typos somewhere, as well as logical errors. Thanks in advance.

<!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>

It should be noted perhaps that any client side validation really needs to be backed up with validation server side as it is fairly trivial to bypass much that you would hope to accomplish with Javascript. Also, if someone were to target the form using, for instance, PHP & cURL none of the Javascript validation routines here would be used at all. In essence do not rely upon client side validation.

With that said there exist in HTML5 a range of attributes and elements that aid you in the task of client-side validation. A form element can have the required attribute set - the form will not be submitted until that field has a value. If the format of that field needs to be in a certain form you can assign a pattern attribute ( basically a RegExp style pattern ) and again, if the field value does not match that pattern the form will not be submitted.

The validation function was really only taking the constituent elements of the user's date of birth for validation and ignoring the other fields. By having a single function for the validation you can try to ensure that all the form elements are utilised in the validation tasks.

I hope the below might help a little - it was just what I came up with and is far from perfect but might be of use.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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