I'm trying to validate an email form with jQuery, and it isn't working, here is the part of the code I think the problem is:
if (isValid == false) {
event.preventDefault();
}
I get the message that event is deprecated, what does this mean and how can I fix it?
EDIT (here's the whole code):
$("#contact_form").submit( evt => {
let isValid = true;
// validate the first name entry
const firstName = $("#first_name").val().trim();
if (firstName == "") {
$("#first_name").next().text("This field is required.");
isValid = false;
} else {
$("#first_name").next().text("");
}
$("#first_name").val(firstName);
// validate the last name entry
const lastName = $("#last_name").val().trim();
if (lastName == "") {
$("#last_name").next().text("This field is required.");
isValid = false;
} else {
$("#last_name").next().text("");
}
$("#last_name").val(lastName);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
Change event to evt.
if (!isValid)
{
evt.preventDefault();
}
The event you're trying to prevent is the one from the 'submit' listener. Not the global event.
$("#contact_form").submit( evt => { });
Related
After a user sign in successfully, I want to use the User UID to verify the user has selected the right school, I have been able to achieve this task, but the problem is, I have to click the login button twice before an action takes effect.
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
}
It is very unusual to have an onAuthStateChanged listener in a click handler like that. More likely you want something like:
...
} else {
toggleSignIn();
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
By the way: if you can look up the school for the user with a query, is there any specific reason why you don't simply prepopulate that value for them in the form?
Your code has a flaw. onAuthStateChanged listener is attached every time the button is clicked. This could add multiple listeners and the same code triggered multiple times after each repeated click. onAuthStateChanged listener should be attached only once when the document is loaded. Your code should be something like:
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
}
}
document.onload = function () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
I assume toggleSignIn() function is used to sign in and will change the firebase AuthState on successful sign in.
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.
var toValidate = jQuery("#fullname, #address, #city, #state,#zip,#phone,#country,#expireMM,#expireYY,#card_number,#cvv_number"),
valid = false;
toValidate.keyup(function () {
if (jQuery(this).val().length > 0) {
jQuery(this).data('valid', true);
} else {
jQuery(this).data('valid', false);
}
toValidate.each(function () {
if (jQuery(this).data('valid') == true) {
valid = true;
} else {
valid = false;
}
});
if (valid === true) {
jQuery("#signInSubmit").prop('disabled', false);
} else {
jQuery("#signInSubmit").prop('disabled', true);
}
});
Above jquery validation working for all field excepting cvv.when i submit form if all field blank button remain disabled after filling all fields button enable but this not working for cvv field if all fields blank and i fill cvv field form submit and disable attribute remove.
The problem is here :
toValidate.each(function () {
if (jQuery(this).data('valid') == true) {
valid = true;
} else {
valid = false;
}
});
Here while checking all elements, cvv is the last element and as per the condition the value valid will be true. And because of it the your button is getting enabled.
You can do something like this :
var valid = true;
toValidate.each(function () {
if (jQuery(this).data('valid') == true && valid !== false) {
valid = true;
} else {
valid = false;
}
});
improve the code as per your requirement.
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.
I have a sign-up form which prompts for the first name, last name, username, password and e-mail address. I'm using two separate $.get() methods to check if the username and e-mail address are not existing.
This is my function:
function validateSignUp() {
var firstName = $("#first-name").val();
var lastName = $("#last-name").val();
var username = $("#username").val();
var password = $("#pass").val();
var email = $("#email").val();
var passwordVerifier = $("#retype-pass").val();
var emailVerifier = $("#retype-email").val();
errorMessage = "";
var isUsernameValid = validateUsername(username);
var isError = false;
// validate first name field
if (firstName == "" || lastName == "") {
isError = true;
$("#error-message").html("All fields are required");
}
// validate password
if (validatePassword(password) == false) {
isError = true;
$("#check-password").html("Password is invalid");
}
else {
$("#check-password").html("");
}
// validate password verifier
if (passwordVerifier == password) {
if (validatePassword(passwordVerifier) == false) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters");
}
else {
if (password != passwordVerifier) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters ");
}
else {
$("#recheck-password").html("");
}
}
}
else {
isError = true;
$("#recheck-password").html("Passwords didn't match");
}
// validate username field
if (isUsernameValid == false) {
isError = true;
$("#check-username").html("Alphanumeric characters only");
} // if
else if (isUsernameValid == true) {
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
} // else
// validate e-mail address field
if (validateEmail(email) == false) {
isError = true;
$("#check-email").html("Sorry, the e-mail you typed is invalid");
} // if
else if (validateEmail(email) == true) {
$.get("/account/checkavailabilitybyemail", { email: email },
function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
}
else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
});
}
if (isError == true) {
return false;
}
return true;
}
When other fields are blank and the username and/or e-mail address is existing, the form is not submitted. And the callback functions of the get methods are called as well. But when I'm going to submit my form with no empty fields, it is automatically submitted without checking the username and/or e-mail by $.get(). Is there anything wrong with my function or I'm not yet discovering something. Thanks.
You need to use a full ajax() call and set the async property to false. This makes your request synchronous, i.e. it forces the browser to wait until doing anything else. Try this:
$.ajax({
url: "/account/checkavailabilitybyemail",
data: { email: email },
async: false,
success: function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
} else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
})
});
if (isError == true) {
return false;
}
I suggest you leverage Jquery validate with two remote rules. It's quite easy to implement and a very mature plugin. This way you can focus on other aspects of your UX and not have to re implement this validation logic should you need to validate another form in your project.
Inside your main function, you cannot directly wait for the $.get() to return. But you can move the form submission to the success callback of the AJAX call (assuming form to contain a reference to the actual form element):
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
form.submit();
//--------------------------^
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
Note however, that then the form submission depends on the AJAX to return. Most useful would be a timeout (with window.setTimeout()) and a server-side validation, if the JS doesn't respond or the user has JS disabled.