user3972776
user3972776

Reputation:

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.

Upvotes: 0

Views: 66

Answers (4)

Raaghu
Raaghu

Reputation: 2014

There is some bug in code pen

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

Upvotes: 0

Dane
Dane

Reputation: 83

call validateForm() method here

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

Upvotes: 0

nanobar
nanobar

Reputation: 66355

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

Upvotes: 0

Manwal
Manwal

Reputation: 23816

Try this:

onsubmit="return validateForm();"

instead of

onsubmit="validateForm();"

DEMO

Upvotes: 1

Related Questions