JavaScript exit method - javascript

I have a JavaScript method that i want to validate a form
if the validation fails so
if (validationChecks ...... ){
return alert("message")
}
else{
//proceed
}
however no matter what i do in the if the form still seems to submit, any ideas?

you should return false after checking validation.
if (validationChecks ...... ){
alert("message")
return false; }
else{
//procced
}

You have spelt 'return' wrong. Also, returning an alert will not work, you'll need to return false explicitly to stop the form submitting.
if (validationChecks ...... ){
alert("message");
return false;
}
else{
//procced
}

Your validation must return false when the form is not valid, and if you're calling your validationin onSubmit, then you must make sure that you include a return statement there as well:
<form onSubmit="return validationChecks();">

You need to return false; in the case of failure

Related

How to find value (true or false) from AJAX response?

I have written a script register user. And in the last step I need value true or false from a function to find that email is already existed or not.
function do_register(user_email){
if (!isemailexist(user_email)) {
document.getElementById("error").innerHTML="email is already exist, please change!!";
document.regForm.user_email.focus()
return false;
}
if (user_email=="") {
document.getElementById("error").innerHTML="email is emphy!!";
document.regForm.user_email.focus()
return false;
}
if(document.regForm.user_name.value!=""){ process_register();} }
function isemailexist ()
xmlHttp.onreadystatechange=function () {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var str=xmlHttp.responseText;
var res=JSON.parse(str);
if (res[0]=="no"){
return false;
}
}
haha=xmlHttp.onreadystatechange.test(res[0]); ///I used test(); methode in order to find value true or false
}
I have tried alot but none of them could give me true or fals !
I have updated my script above, I hope it´s better. Some more code:
PHP CODE
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}
You're doing things bit too complicated. There's no need of making an array when the response is simply false, as you're already telling the user that the email already exists.
Instead of doing
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}
Just do this in your server side.
if(mysql_num_rows($result)>0){ // email is already exist
return false;
}
As you're no longer using an array, your response changes, and you need to adjust your code a little bit. Remove [0] from res[0].
Then your server response will be false, so change
if (res[0]=="no"){
return false;
}
to
if (res==false){
return false;
}
else{
//continue...
}

Validate form using jQuery

When a form submit button is clicked, a function to validate all the field is to be called. Nothing is to happen, however, if the validation fails.
I am using mailto: as my action, does this make a difference?
I would like to get clarification on two things:
Is this the correct way to call a function when clicking the submit button?
$(document).ready(function(){
$('#contactForm').submit(function(){
checkMail();
});
});
Can I still validate the fields even though I'm using mailto:?
Here is the rest of the code:
function checkEmail(){
var email = document.contact.email.value;
if(email == "") {
document.getElemtById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
HTML:
<form name="contact" action="mailto:exampleemail#hotmail.com" method="post">
<li>
<label for="email">Email</label>
<input id="email" type="text" name="email" placeholder="Enter Email Address">
</li>
<span id="email_error"></span>
Further, I don't get an error message on clicking submit.
No, you need the event handler to return false in case the validation failed. This will prevent the action from being executed, i.e. the mail program from being launched.
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Source
Modify it like this:
$(document).ready(function(){
$('#contactForm').submit(function(){
return validate();
});
});
Of course, this implies that the validate() function needs to actually return false in case the validation fails, and true otherwise.
Further you are missing id="contactForm" on your <form> tag.
Also, you need to grab the email value correctly:
var email = $("#email").val();
There's another mistake: You misspelled getElementById(). Here's a corrected version:
function checkEmail() {
var email = $("#email").val();
if (email == "") {
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
Or alternatively, using all jQuery:
function checkEmail() {
var email = $("#email").val();
var $error = $("#email_error");
if (email == "") {
$error.html("No Email Address");
return false;
}
else {
$error.html("");
return true;
}
}
Here's what you need:
$(document).ready(function(){
$('#contactForm').submit(function(){
if (!validate()) {
return false; // Prevent the submit
}
});
});
For validating the fields of your form, before sending it, you can use the jQuery's validation plugin:
$(document).ready(function(){
$("#contactForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
});
Check the online doc for more information and examples: http://docs.jquery.com/Plugins/Validation#Validate_forms_like_you.27ve_never_been_validating_before.21

Ajax validation in form update in yii

I have a form for both creation and editing some fields.I am using Ajax validation for that before submitting the form like
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'candidates-profiles-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>false,
'beforeValidate'=>"js:function(form) {
if((form.data('submitObject')[0].id ) == 'cancel'){
alert('cancalclicked');
this.validateOnSubmit = false;
this.validateOnChange = false;
this.beforeValidate = ''; // the problem is caused by this line
form.submit();
return false;
}
else{
alert('submitclicked');
return true;
}
}",
'afterValidate'=>"js:function(form, data, hasError) {
if(hasError) {
alert('We have detected some input errors and has not saved your data. Please click Ok to correct them.');
return false;
}
else {
if(confirm('We have validated your input and we are ready to save your data. Please click Ok to save or Cancel to return to input.'))
return true;
else
return false;
}
}",)
)); ?>
After creation it is perfectly coming in afterValidate function and works fine.But after editing it is not all coming in afterValidate. But it is coming in beforeValidate and submitting the form with out reaching afterValidate .
Make sure you have $this->performAjaxValidation($model); in your controller for that action.

Form shows mistakenly the success alert box when it has invalid input in jQuery

In the script below I check if the email entered is valid. It is not the best regex but it is ok for now. Also for the moment I do not make any server side check for input. Only with this script.
I have this problem though:
When an email is valid, and after I type an invalid email I get first the Your email is not in valid format and then You will be notified when we launch. Thank you! alert. Also the email is sent. How to fix this ?
Thank you
this is my form
<form id="myform" action="" method="POST">
<input id="subscribe" name="subscribe" class="subscribe floatLeft" type="text">
<button id="signUp" class="signUp floatRight" ><intro>notify!</intro></button>
<div class="clear"> </div>
</form>
and here is the script
var signUp = function(inputEmail) {
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(inputEmail)) {
isValid = false;
alert('Your email is not in valid format');
}
$("#myform").submit(function(event) {
event.preventDefault();
if (!isValid) {
return false;
} else {
$.post('mailme.php', $("#myform").serialize(), function(data) {
alert('You will be notified when we launch. Thank you!');
});
return false;
}
});
};
You need the onsubmit event to return false;
You need to bind the submit event anyway and make the isValid check there;
$("#myform").submit(function(event){
event.preventDefault();
if(!isValid){
return false;
}else{
$.post(...)
return false;
}
});
--Edit--
Forgot to return false/event.preventDefault; But like i said, the submit event need to be bound anyway
--Edit2--
function validEmail(email){
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email.test(emailReg)
}
$(document).ready(function(){
$("#myform").bind({
submit: function(e){
e.preventDefault();
if(validEmail($("#myform").find("#subscribe").val()){
$.post(...)
alert("You will be notified");
return false;
}
else {
alert("Invalid email");
return false;
}
});
});
}
You need to return false or event.preventDefault() in the emailReg test.

Form submission will not stop for validation

What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});

Categories

Resources