0

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.

2
  • 1
    How about you explain what you want your validation to do? Commented Feb 26, 2015 at 11:36
  • it's just for learning purpose as i'm new to javascript and i just want to check a specific input based in pattern Commented Feb 26, 2015 at 11:40

4 Answers 4

1

Try this:

onsubmit="return validateForm();"

instead of

onsubmit="validateForm();"

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

your demo works fine but let's declare that the error wasn't in onsubmit , it was in function (if statement) if (score.match(scoreReg)) { alert("the score pass"); return true; } return false; thanks for your help and code
0
<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.

1 Comment

yeah , this works and i can call it's best practice too .thank you for your time to explain these things
0

call validateForm() method here

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

Comments

0

There is some bug in code pen

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.