I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
Related
I simply want to display an error message such as "Email must contain #" and prevent the form from submitting, if there is an error.
How can I go about doing this?
My latest attempt which is a failure:
const email = document.getElementById('email')
const emailmessage = document.getElementById('emailmessage')
const regex = ('^\S+#\S+$')
form.addEventListener('submit', function (event) {
if(!email.value.match(regex)) {
emailchecker();
event.preventDefault();
}
});
let emailchecker = function() {
if(!email.value.match(regex)) {
document.getElementById('emailmessage').innerHTML = '<img src="222.svg" height="15"/> Email Error';
}
Your code is correct, you only need the regex for email validation:
function emailchecker (emailAdress){
let regexEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (emailAdress.match(regexEmail)) {
return true;
} else {
return false;
}
}
let emailAdress = "test#gmail.com";
console.log(emailchecker(emailAdress)); //return true
I want to validate my data with jQuery or Javascript and send them to the server but why aren't they validated?
$(document).ready(function() {
var name = $('#signup-name').val();
var email = $('#signup-email').val();
var password = $('#signup-password').val();
var email_regex = new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
var pass_regex = new RegExp(/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/);
$('#signup-form').on('submit', function(e) {
e.preventDefault();
if (validate()) {
$.ajax({
type: 'post',
url: 'signup',
data: {
email: email,
password: password,
name: name
},
});
} else {
return false;
};
});
function validate() {
// name cheak here
if (name.length == "") {
$('.nameerror').html("Name field required !");
return false;
} else if (name.length = < 3) {
$('.nameerror').html("Name Should be greater than 3");
return false;
};
// email cheak here
if (email.length == "") {
$('.emailerror').html("Email field required !");
return false;
} else if (!email_regex.test(email)) {
$('.emailerror').html("Please enter correct email.");
return false;
};
// password cheak here
if (password.length == "") {
$('.passerror').html("password field required !");
return false;
} else if (!pass_regex.test(password)) {#
('.passerror').html("Minimum eight characters, at least one letter and one number:");
return false;
};
};
});
There are two major issues, you were just not passing the arguments to the validate function. I have updated your code with arguments passed to the function.
Furthermore, you never returned true for any function as a result nothing would be returned. Also your if statements are split and will contradict.
I have corrected these issues, hopefully this should work!
$(document).ready(function() {
$('#signup-form').on('submit', function(e) {
var name = $('#signup-name').val();
var email = $('#signup-email').val();
var password = $('#signup-password').val();
e.preventDefault();
if (validate(name, email, password)) {
$.ajax({
type: 'post',
url: 'signup',
data: {
email: email,
password: password,
name: name
},
});
} else {
return false;
};
});
});
function validate(name, email, password) {
var email_regex = new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
var pass_regex = new RegExp(/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/);
// name cheak here
if (name.length == 0) {
$('.nameerror').html("Name field required !");
return false;
} else if (name.length <= 3) {
$('.nameerror').html("Name Should be greater than 3");
return false;
} else if (email.length == 0) { //Check Email
$('.emailerror').html("Email field required !");
return false;
} else if (!email_regex.test(email)) {
$('.emailerror').html("Please enter correct email.");
return false;
} else if (password.length == 0) { // password cheak here
$('.passerror').html("password field required !");
return false;
} else if (!pass_regex.test(password)) {
('.passerror').html("Minimum eight characters, at least one letter and one number:");
return false;
} else {
return true;
}
};
I believe the issue is that, although the validate function does indeed have access to the variables name etc, these are just set once when the document is first ready, and never updated. The values of the variables should be set inside the event handler for the submit event, before validate is called.
I have a javascript function that validate a popup form before submit it. Unfortunately it's created to handle one popup form per page only.
In my case, i have two different popup forms, so i want to specify what to do and also for which one.
$.fn.goValidate = function() {
var $form = this,
$inputs = $form.find('input:text');
var validators = {
email: {
regex: /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/
}
};
var validate = function(klass, value) {
var isValid = true,
error = '';
if (!value && /required/.test(klass)) {
error = 'This field is required';
isValid = false;
} else {
klass = klass.split(/\s/);
$.each(klass, function(i, k){
if (validators[k]) {
if (value && !validators[k].regex.test(value)) {
isValid = false;
error = validators[k].error;
}
}
});
}
return {
isValid: isValid,
error: error
}
};
var showError = function($input) {
var klass = $input.attr('class'),
value = $input.val(),
test = validate(klass, value);
$input.removeClass('invalid');
$('#form-error').addClass('hide');
if (!test.isValid) {
$input.addClass('invalid');
if(typeof $input.data("shown") == "undefined" || $input.data("shown") == false){
$input.popover('show');
}
}
else {
$input.popover('hide');
}
};
$inputs.keyup(function() {
showError($(this));
});
$inputs.on('shown.bs.popover', function () {
$(this).data("shown",true);
});
$inputs.on('hidden.bs.popover', function () {
$(this).data("shown",false);
});
$form.submit(function(e) {
$inputs.each(function() {
if ($(this).is('.required') || $(this).hasClass('invalid')) {
showError($(this));
}
});
if ($form.find('input.invalid').length) {
e.preventDefault();
$('#form-error').toggleClass('hide');
}
});
return this;
};
$('form').goValidate();
I'm pretty sure that it's all about this line:
$('form').goValidate();
Let's say that the first form id is form_1 and the second form_2.
What should i put in this line?
Something like this i guess:
$('form['form_1]').goValidate();
Hope it was clear, thanks !
You can use form id to target your form.
ex. if your first form has id form1 then you can write.
$('#form1').goValidate();
and same as second one.
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
I'm working on a validation form, I'm sending the data from the html fields with JS pulling the validation with a php document and sending it back via AJAX, it works pretty fine in Chrome but not Internet Explorer (I'm testing it in IE9):
function Checkfiles() {
var fup = document.getElementById('flUpload');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
var chkext = ext.toLowerCase();
if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") { return true; } else { return false; }
} // Checkfiles
function Checksize() {
var iSize;
if ($("#flUpload")[0].files[0]){ iSize = ($("#flUpload")[0].files[0].size / 1024);}
if(Checkfiles()==true && iSize <= 51.200) { return true; } else { return false; }
} //Checksize
$(document).ready(function() {
$("#ff1").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function (response) {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response)=='b' && Checksize()==true) {
this.submit(); // submit, bypassing jquery bound event
}
else {
if (Checksize()==true) {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');
} else {
if(response!='b') {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'<li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>');
} else { $("#ajax_call_val").html('<div id="validation"><ul><li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>'); }
}
}
}
});
});
});
Any wonder why is not working in IE? Thanks in advance.