I am making simple auth form with some messages for user while he is typing the username/email in the input. Before form submission code works just fine, but after I submit the form (with preventDefault) this 'input-checker' stops working. Can anyone tell me why and how to make it work?:-)
var reValidEmail = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
$("#auth-input").on('input', function () {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
if (!reValidEmail.test(document.getElementById("auth-input").value)) {
$("#login-comment").text("Please enter valid email");
} else {
$("#login-comment").text("");
}
}
});
$("#log-in-form").submit(function (e) {
e.preventDefault();
if ( document.getElementById("auth-input").value.length > 0
&& ( document.getElementById("auth-input").value.indexOf("#") == -1
|| ( document.getElementById("auth-input").value.indexOf("#") + 1
&& reValidEmail.test(document.getElementById("auth-input").value)
)
)
) {
//some ajax request
} else {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
$("#login-comment").text("Please enter valid email"); //does not hide after form submission and input change for correct one
} else {
$("#login-comment").text("Please enter username or email"); //does not hide after form submission and input change for correct one
}
}
});
Related
I have the code below and I would like it to perform multiple field validation and give alert on each field when it is incomplete. Scenario: If I use the code without the validation and associated alerts it works 100%, when I include the validation the code goes through each step and alert and ultimately fails on the last bit to execute and flag a field as 'true' and gives error of 'Invalid or unexpected token'. Any help would be welcome
{
!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")
}
var x;
if ('{!Case.Trigger_Submit_Spark__c}' == true || '{!Case.Spark_Service_Desk_Ref__c}' != "") {
alert('You are unable to submit request, as this request has already been submitted to Spark')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as Spark Service Request Type and Request note are blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' != "") {
alert('You are unable to submit request, as Spark Service Request Type is blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' != "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as the Spark Request Note is blank')
} else {
if ('{!Case.Trigger_Submit_Spark__c}' == false && confirm('Do you want to submit this request?\n\nBy submitting this request the following will occur:\n 1. Case Status changed to Escalated to Tier2\n 2. Escalation Group = Spark\n 3. Email sent to Spark (Remedy)\n 4. Note placed in SalesForce chatter feed\n\nPlease check chatter feed to confirm that request has been sent') == true) {
x = "OK";
var c = new sforce.SObject("Case");
c.id = '{!Case.Id}'
c.Trigger_Submit_Spark__c = true;
result = sforce.connection.update([c]);
if (result[0].success === "true") {
window.location.reload();
} else {
alert("An Error has occured. Error: " + result[0].errors.message);
}
}
}
}
}
}
I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}
I'm trying to show errors in real time on my registration form, instead of being redirected to another page (register.php).
The index page on my site has a sign-up link which opens a popup registration form (registration.HTML) in a new window. When a user submits this form
it calls on register.PHP as an action. Inside register.php there is a line of code:
js_include('js/register.js');
This javascript checks that certain data is submitted correctly within registration.html. I'd like this check to be performed before submitting the form
and causing it to redirect to register.php. I only need it to direct to register.php if javascript says everything is good.
You can test this yourself here If you click "sign up" in the top-right corner, and type in gibberish as the email and press Enter, it will redirect to register.php and show the error at the bottom (if you scroll down). I'd like this error to be displayed on the registration form.
I tried including the js below within some script tags on my html page, but it still redirects me.
Here is register.js, all feedback is welcome! Thank you
$(document).ready(function() {
$('.formFieldWarning').hide();})
function checkRegisterFormSubmit() {
$('.formFieldWarning').hide();
var errors = 0;
// Check the user name
if($('#username').val() == '') {
$('#username_warning1').show();
errors++;
} else {
if ($('#username').val().length < 2 ) {
$('#username_warning2').show();
errors++;
}
}
// Check the password
if ($('#password').val().length < 2 ) {
$('#password_warning1').show();
errors++;
} else {
if ($('#password').val() == $('#username').val() ) {
$('#password_warning2').show();
errors++;
}
}
// Check the password_verification
if ($('#password_verification').val() != $('#password').val() ) {
$('#password_verification_warning1').show();
errors++;
}
// Check the email address
if($('#email').val() == '') {
$('#email_warning1').show();
errors++;
} else {
if ($('#email').val().search(/^\w+((-|\.|\+)\w+)*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,63}$/) == -1) {
$('#email_warning2').show();
errors++;
}
}
if (errors != 0) {
$('#form_not_submit_top').show();
$('#form_not_submit_bottom').show();
return false;
} else {
return true;
}
}
Here is an example of how to test a form field using jQuery's blur() function -
$('input[name="foo"]').blur(function() {
var currentValue = $(this).val();
var testValue = 'crumple';
if(currentValue != testValue) {
$(this).next('span').html('FAIL');
} else {
$(this).next('span').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="foo" type="text" /><span></span>
When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"
Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("#");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
document.forms.contactform.email.focus();
return false;
}
return(true);
}
function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
var numbers = document.forms.contactform.phone.value;
var verified = re.exec(numbers);
if (!verified)
{
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
return(true);
}
function validateentry()
{
if(document.forms.contactform.name.value=="")
{
alert("Please provide your name.");
document.forms.contactform.name.focus();
return false;
}
if(document.forms.contactform.company.value=="")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
document.forms.contactform.company.focus();
return false;
}
if(document.forms.contactform.email.value == "")
{
alert("Please provide an Email address.");
document.forms.contactform.email.focus();
return false;
}else{
var validformat=validateemail();
if(validformat==false)
{
return false;
}}
if(document.forms.contactform.phone.value=="")
{
alert("Please provide a phone number in the format 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
alert("Please provide the phone number in the format of 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else
{
var validnumber=validatephonenumber();
if(validnumber==false)
{
return false;
}}
if(document.forms.contactform.msg.value=="")
{
alert("Please provide a message.");
document.forms.contactform.msg.focus();
return false;
}
return(true);
}
It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes? Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com
Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...
Validation JavaScript:
function validateemail(e)
{
var emailentry = e.value
, at = emailentry.indexOf("#")
, period = emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
e.focus();
return false;
}
return true;
}
function validatephonenumber(e)
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
, numbers = e.value;
if (!re.exec(numbers))
{
alert("Please enter a phone number in the format of 999-999-9999");
e.focus();
return false;
}
return true;
}
function validateentry(f)
{
if(f.name.value == "")
{
alert("Please provide your name.");
f.name.focus();
return false;
}
if(f.company.value == "")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
f.company.focus();
return false;
}
if(f.email.value == "")
{
alert("Please provide an Email address.");
f.email.focus();
return false;
}
else
{
var validformat = validateemail(f.email);
if(validformat == false)
{
return false;
}
}
if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
{
alert("Please provide the phone number in the format of 999-999-9999.");
f.phone.focus();
return false;
}
if(f.msg.value == "")
{
alert("Please provide a message.");
f.msg.focus();
return false;
}
return true;
}
I am using a validation plugin for my form but after the standard validation i want to add my own methods one of them is a Ajax function which checks if email already exists.
Both work but if i for example enter a email it does the Ajax method, where i want to put a redirect.
the problem is that even if not all fields are filled it always redirects. It has to check al standard validation first, then do the ajax if all is OK then submit how do I do this ?
$( "#registration-form" ).submit(function( event ) {
//vars
var contactemail = $('#contactemail').val();
var contactpassword = $('#contactpassword').val();
//Global validation
$.validate({
onError : function() {
//alert('Validation failed');
return false;
}
});
//If User create - check if user exists
if($('#contactemail').length && $('#contactemail').val().length && $('#contactpassword').length && $('#contactpassword').val().length)
{
//Check if can create user
$.post(jssitebaseUrl+'/ajaxFile.php',{'contactemail':contactemail,'action':'checkOrderEmailId'}, function(output){
//alert(output);
if(output == 'UserExist' && contactpassword !=""){
$("#errors").show();
$('#errors').html('<p class="i">Can not create account</p>');
$('html, body').animate({scrollTop:0}, 'slow');
return false;
}
else if(output == 'CanCreateAccount' || (output == 'UserExist' && contactpassword =="")){
alert("Maak een guest order aan")
//redirect...
document.checkoutform.submit();
}
});
}
event.preventDefault();
});
Try checking if form is valid before posting:
if ( $("#formId").valid() ) {
// ajax call
}