Reputation: 5325
In my view I have:
<div class="form-group registration_form">
<%= form_tag(register_learner_path, {remote: true}) do -%>
<p>
<%= label_tag :email %>
<%= text_field_tag :email %>
<p/>
<p>
<%= label_tag "First Name" %>
<%= text_field_tag :first_name %>
<p/>
<p>
<%= label_tag "Last Name" %>
<%= text_field_tag :last_name %>
<p/>
<%= hidden_field_tag 'event_id', @event.id %>
<p class="submit_register">
<%= submit_tag "Register for this event", id: 'register_button', :onclick => "return validateform();" %>
<span class="help-block">Enter your name and email above and the link will be magically revealed</span>
<p/>
<%- end -%>
</div>
...and my coffeescript is:
jQuery ->
if $('div').hasClass 'form-group registration_form'
$(".location").hide()
$(".location-section-link").hide()
$(".submit_register").click ->
validateForm()
if validateEmail($("#email").val()) == false
alert('Please enter a valid email address')
return false
else
$(".location").show()
$(".location-section-link").show()
$(".registration_form").hide()
#validate email
validateEmail = (email) ->
re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
re.test email
#validate email, first name and last name
validateForm = ->
if $("#email").val() == '' || $("#first_name").val() == '' || $("#last_name").val() == ''
alert('Please enter first name, last name, and email')
return false
Essentially I am trying to accomplish two validations here. One I want to ensure no empty strings in email, first name and last name. Second, I want to verify a 'valid' email based on the regex in the js.
The behavior I am seeing with this code is that both the validations are running, however I only want the email validation to run IF the other validation (test of empty strings) passes.
Upvotes: 0
Views: 884
Reputation: 5325
So this feels a little busy, but it works. Feel free to make suggestions...
jQuery ->
$group = $('.form-group.registration_form')
if $group.length
$(".location").hide()
$(".location-section-link").hide()
$(".submit_register").click ->
if validateForm() == false
return false
else if validateEmail($("#email").val()) == false
alert('Please enter a valid email address')
return false
else
$(".location").show()
$(".location-section-link").show()
$(".registration_form").hide()
#validate email
validateEmail = (email) ->
re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
re.test email
#validate email, first name and last name
validateForm = ->
if $("#email").val() == '' || $("#first_name").val() == '' || $("#last_name").val() == ''
alert('Please enter first name, last name, and email')
return false
Upvotes: 2