Email validation Jquery not working - javascript

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)
}

Related

How to validate a form in jQuery?

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.

Clearing specific fields (not all) when a form is submitted

Im trying to clear only the password and confirm password fields when those are not matched.
Im calling a function when the submit button is pressed which contains a password checking condition. How should I clear only password and confirmpassword inputs if that condition is true?
function checkmatch()
{
var name = $("#username").val();
var address = $("#address").val();
var email = $("#emailid").val();
var mobile = $("#phonenum").val();
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
return false;
}
else if((name==null || name == "") || (address==null || address == "") || (email==null || email == "") || (mobile=null || mobile == "") || (password==null || password == "") || (cnfirmPassword==null || cnfirmPassword == ""))
{
alert("Please fill all the required fields.");
return false;
}
else
{
$.ajax(
{
type: "POST",
url: "assmt1.php",
datatype: "html",
data: $("#fm1").serialize(),
success: function(response)
{
}
});
alert("Your form has been submitted. Thank you!");
}
}
Is this what you mean?
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
$("#newPwd").val('').focus(); ///this will not focus because of alert
$("#confirmPwd").val('');
return false;
}
All you need to do is call the same function you used to get the value.
Just pass empty string to val() like so:
$("#newPwd").val('');
$("#confirmPwd").val('');

Other else if statement not executed

Problem: The first conditional statement else if was performed, But the next else if statement was not performed. It should performed if both username and password are empty. What did I missed?
$(document).ready(function(){
$("#submit").click(function(e){
var username = $("#username").val();
var password = $("#password").val();
if(username == ""){
alert("account id required");
}else if(password == ""){
alert("password required!");
}else if((username == "" || username == null) && (password == "" || password == null)){
alert("All fields of information is required!");
}else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username="+username+"&password="+password,
success:function(data){
if(data == "success"){
window.location.href="main.php";
}else if(data == "unsuccess"){
alert("Invalid account id/password");
$("#username").val('');
$("#password").val('');
}
}
});
}
return false;
});
});
If, else if, else if, else.. In this hierarchy. Any one and only one block will execute.. If your intention is to execute the second else if .. Then make it if...
So your code should be like below.
if((username == "" || username == null) && (password == "" || password == null)){
alert("All fields of information is required!");
}
else{
if(username == ""){
alert("account id required");
}else if(password == ""){
alert("password required!");
}
}
You have to put the condition containing both username and password before the other ones.
if it gets inside an if statement it wont try with the next else, so if it performs the first else if, it won't check the next else if.
you need to do something like this
if(!username && !password){
alert("All fields of information is required!");
}else if(!username){
alert("account id required");
}else if(!password){
alert("password required!");
}else{
here the rest of your code
}

username and password validation using javascript

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.

Can I wait for $.get() call before submitting the form?

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.

Categories

Resources