简体   繁体   中英

Validating Input in javascript didn't work

why this simple javascript code didn't run properly http://codepen.io/anon/pen/wBXKQY html

 <form id="scoreForm" name="scoreForm"  onsubmit="validateForm();">


            <label for="score">Score:</label>
            <input id="score" name="score" />
            <input type="submit" value="submit" />


    </form>

js

  function validateForm() {

            var score = document.getElementById("score").value;
            var scoreReg = /^\s*(\+|-)?\d+\s*$/;

            if (score.match(scoreReg))
            { alert("the score pass"); return false; }

        }

i just need to perform validation that is beyond the capabilities of the HTML5 input attributes.

Try this:

onsubmit="return validateForm();"

instead of

onsubmit="validateForm();"

DEMO

<form id="scoreForm" name="scoreForm">
    <label for="score">Score:</label>
    <input id="score" name="score" />
    <input type="submit" value="submit" />
</form>

<script>
document.getElementById('scoreForm').addEventListener('submit', validateForm);

function validateForm(ev) {

  var scoreVal = +document.getElementById('score').value;

  if (scoreVal < 10) {
    alert('Sorry your score is too low!');
    ev.preventDefault();
  }
}
</script>

Pen: http://codepen.io/ferahl/pen/GgGpLd

Notes:

Better to not really use IDs for anything, use classes, query them with document.querySelector or document.querySelectorAll .

The + you see there converts to a number (it's shorthand)

Better to use "unobtrusive" javascript - I add the event handler in JS using addEventListener

preventDefault stops the form submitting. There is also another useful function called stopPropagation which you can look into. Return false does both - it is better to have an awareness of which or both you want to do.

在这里调用validateForm()方法

<input type="submit" value="submit" onclick="validateForm();"/>

There is some bug in code pen

you can try in w3schools http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit

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