Search code examples
javascriptjqueryclient-side-validation

Can't get my "code" validated by JavaScript


Okay, so for my school project I need to create a page that has a form to input a contest code in a certain format, use javascript to validate it and display a "sorry" message. I believe I have everything correct, but clearly I do not as I am here asking for help. It seems like every time I try to submit the code, the page just refreshes, and my JSFiddle test returns a wonky error. Any help would be appreciated. The code that I am using is below with two JSFiddle links, one with just my code, and one with all of my HTML and my JavaScripting:

<script type="text/javascript">
$('.code_input').on('submit', function(e) {
    e.preventDefault();
    if ($('.code', this).val().match(/^[0-9]{6}\-[0-9]{6}\-[a-z]$/)) {
        alert('Sorry, you did not win.');
    }else{
        alert('Not a valid code. Please try again.')
    }
}); // reference point
</script>

<section class="code_input">
  <form method="post">
    <input type="text" class="code" name="code" placeholder="Type Code Here" />
    <input id="submit" type='submit' value='Check Number'>
  </form>
</section>

JSFiddle - Just the code
JSFiddle - All the code


Solution

  • https://jsfiddle.net/azhzpLct/

    document.querySelector('form').addEventListener('submit', function(e) {
        e.preventDefault();
        if (document.querySelector('.code').value.match(/^[0-9]{6}\-[0-9]{6}\-[a-z]$/)) {
            alert('Sorry, you did not win.');
        }else{
            alert('Not a valid code. Please try again.')
        }
    });