I have this simple problem that I don't know what did I do wrong.
so I have this code:
function validateForm()
{
var validation = true;
validation &= validateUsername();
validation &= validatePassword();
return validation? true:false;
}
function validateUsername()
{
var username = $('#username').val();
if( username == "" )
{
alert("Login failed, Please enter your username");
return false;
}
else if( username != "username" )
{
alert("Login failed, Username Incorrect");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var password = $('#pass').val();
if(password != "password")
{
alert("Login failed, Password is incorrect");
return false;
}
else if(password == "")
{
alert("Login failed, Please enter your password");
return false;
}
else
{
return true;
}
}
If I enter no password it should alert that you should enter your password but instead that it is alerting password is incorrect. Why is it not going through all the if's I created?
You swap the conditions, and check for an empty string before you check for the correct password
function validatePassword() {
var password = $('#pass').val();
if(password == "") {
alert("Login failed, Please enter your password");
return false;
} else if(password != "password") {
alert("Login failed, Password is incorrect");
return false;
} else {
return true;
}
}
right now you're checking if it's not the correct password first, and as an empty string probably isn't the correct password, that matches before the check for an empty string.
Related
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 been working on a simple email validation. But it doesn't work.
Any ideas why it isn't working? Am I doing something wrong or should I structure my code in some other way?
I have done a function like this:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
} else {
return true;
}
}
and after that I'm calling that function in my setupRegistration function.
My JS looks like this:
function doOutputMessage(type, message){
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if(type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if(type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
function setupRegistration(){
$("#signupWrapper").on("click", "#regUser", function(){
var username = $("input[name='username']").val();
var email = $("input[type='email']").val();
var password = $("input[type='password']").val();
if(username == ""){
doOutputMessage("error", "Fill in your desired username!");
}
if(email == ""){
doOutputMessage("error", "Fill in your email!");
}
if(IsEmail(email)==false){
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
ajaxCall(username, email, password);
}
});
}
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
function ajaxCall(username, email, password){
$.ajax({
type: 'POST',
url: '../register.php',
data: {
'username' : username,
'email' : email,
'password' : password,
},
success: function(data) {
if(data.exists){
doOutputMessage("error","That Username is allready taken.");
} else if(data.inserted) {
doOutputMessage("success","You have successfully been registered!");
}else {
doOutputMessage("error","Something went wrong, try again later.");
}
}
});
}
$(document).ready(function(){
setupRegistration();
});
function regSubmit(){
clearErrorMessages();
var username = $("#regForm #username").val();
var email = $("#regForm #email").val();
var password = $("#regForm #password").val();
if(username == ""){
showValidationMessage("#regForm #error_username", "Fill in your desired username!");
}
if(email == ""){
showValidationMessage("#regForm #error_email", "Fill in your email!");
}
if(password == ""){
showValidationMessage("#regForm #error_password", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
$.ajax({
url: 'regLogin.code.php',
type: 'POST',
data: {
'action' : 'register',
'username' : username,
'email' : email,
'password' : password
},
success: function(data, status){
console.log(data);
if(data == "exist"){
showValidationMessage("#regForm #error_general", "A user with that username or password already exists!");
}else if(data == "illegal"){
showValidationMessage("#regForm #error_general", "Your username contains illegal characters!");
}
else if(data == "true"){
showValidationMessage("#regForm #success", "Success!");
setTimeout(function(){
window.location.replace("/admin/inside/");
}, 1000);
}
},
error: function(xhr, desc, err){
showValidationMessage("#regForm #error_general", "Something went wrong, please try again");
}
});
}
}
#Mario-Chueca is right. Your code is mostly working correctly, however, you are making an Ajax call regardless if the email is correct and as a result the error message is not shown. You should only make the ajax call when the specified email is valid:
if(username != "" && email != "" && password != "" && IsEmail(email)){
ajaxCall(username, email, password);
}
I have included a code sample below to show that your email validation (without Ajax call) is working. I have included the if(!IsEmail(email){ fix suggested by #Abdulla and I also also added a more complex regular expression from this post.
function IsEmail(email) {
//var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//More advanced regex to valid 99.99% of most emails in use, see https://stackoverflow.com/questions/46155/validate-email-address-in-javascript
var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if (!regex.test(email)) {
return false;
} else {
return true;
}
}
function doOutputMessage(type, message) {
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if (type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if (type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
//if (IsEmail('john.doe#stackoverflow.com')) {
// doOutputMessage('success', 'valid email')
//}
if (!IsEmail('john.doe#stackoverflow.com')) {
doOutputMessage('error', 'invalid email')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outputMessage">Test</div>
Use some of the advices from before, but change this too, the error doesn't stop the ajax call:
var error_email=false;
if(!IsEmail(email)){
error_email=true;
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != "" && !error_email){
ajaxCall(username, email, password);
}
remove false in here
if(!IsEmail(email){
and regex should be
regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
Live DEMO
How to Find or Validate an Email Address
please try:
function IsEmail(email){
var reg = /^[a-zA-Z0-9\.\-\+]+\#([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/
return reg.test(email)
}
I am trying to validate a form without using html5 validation as an exercise for a class, but I can't figure it out for the life of me.
I want to have an alert message pop up if the email and/or name is not valid/empty.
I have gotten to the point where the alert will pop up form the email OR the name field, depending which is first in the onsubmit function.
Any ideas would be greatly appreciated!
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");
if (inputEmail==="") {
alert("Please enter your email.")
return false;
} else if (!emailPattern.test(inputEmail)){
alert("Please enter a valid email address.");
return false;
} else {
return true;
};
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
alert("Please enter your name.")
return false;
} else if (!namePattern.test(inputName)){
alert("Please enter a valid name.");
return false;
} else {
return true;
};
};
You return after the first one is validated, so the second field is never checked. Instead, have a local variable that is set to true by default, and set to false of either of the fields fail validation, and return it at the end.
var valid = true;
// ...
if(inputEmail==="") {
alert("Please enter your email.");
valid = false;
// ...
return valid;
};
Maybe this doesn't work but the concept could be something like this...
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"),
error = [],
i = 0;
if (inputEmail==="") {
error.push("Please enter your email");
} else if (!emailPattern.test(inputEmail)){
error.push("Please enter a valid email address.");
}
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
error.push("Please enter your name.")
} else if (!namePattern.test(inputName)){
error.push("Please enter a valid name.");
}
if(typeof error !== 'undefined' && error.length > 0){
alert("you submit the form correctly");
} else {
for(i = 0; i < error.length; i + 1){
alert(error[i]);
}
}
};
I'm in the middle of coding CAPTCHA in JavaScript, and I'm trying to get the validation for a contact form to work properly. I'm almost there, the form won't be submitted until the CAPTCHA text-field is entered, but the problem is I'm still getting an error message when I entered the CAPTCHA code correctly.
<script>
function ValidateContactForm()
{
var name = document.ContactForm.name;
var phone = document.ContactForm.phone;
var code = document.ContactForm.code;
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter a valid phone number..");
phone.focus();
return false;
}
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
code.focus();
return false;
}
else {
return true;
}
return true;
}
</script>
Any help would be greatly appreciated. Thanks.
Check this lines, the problem is here:
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
^^^^^^^^^^^^^
code.focus();
^^^^^^^^^^^^^
return false;
^^^^^^^^^^^^^
}
else {
return true;
}
This code will return false every time.
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.