Matt
Matt

Reputation: 1257

How to check if HTML form validation passed and trigger event

I have a form with HTML validation for telephone number. I need to be able to validate that the input is valid, and only if its valid, to trigger a mixpanel event. I can validate the input, but having trouble figuring out if the input is validated and triggering the event.

HTML

<form class=contact method=get action="/" accept-charset="UTF-8" id="form">
<input type="tel" class="text phoneNumber" name="tel" placeholder="Phone number" required>
<input type=submit class="submit appended" value=submit>
</div>

jQuery

$(".submit").click(function () {
//check if form validation passed
if ($(".phoneNumber") == true) {
    //if passed, trigger mixpanel event
}
});

JSFIDDLE: LINK

Upvotes: 3

Views: 3138

Answers (1)

PeterKA
PeterKA

Reputation: 24638

There are two approaches you can take .... great comment from @axel.michel. If you use the form's submit event instead of the submit button's click event, the submit event only triggers only when the form is valid:

$('form.contact').on('submit', function(e) {
    //FORM IS VALID 
    //stop default form submission so you can do stuff
    e.preventDefault();
    //do stuff
    //submit form if desired
    this.submit();
});

$('form.contact').on('submit', function(e) {
    e.preventDefault();
    console.log( $('.phoneNumber')[0].checkValidity() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class=contact method=get action="/" accept-charset="UTF-8" id="form">
<input type="tel" class="text phoneNumber" name="tel" placeholder="Phone number" required>
  
<input type=submit class="submit appended" value=submit>
</div>

The second approach, if all you want is a way to check that the input element is valid is to add a button for doing that:

$('.button').on('click', function() {
    console.log( $('.phoneNumber')[0].checkValidity() );
});

$('.button').on('click', function() {
    console.log( $('.phoneNumber')[0].checkValidity() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class=contact method=get action="/" accept-charset="UTF-8" id="form">
<input type="tel" class="text phoneNumber" name="tel" placeholder="Phone number" required>
<button type="button" class="button">Check Validity</button>  
<input type=submit class="submit appended" value=submit>
</div>

Upvotes: 5

Related Questions