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 validating a form and then asking for the confiormation through javascript…
so on submit i have called two function name validate() & make_confirm()..
onsubmit="return(validate() && show_alert(this));"
by this i am partially able to call both function but confirmation part is not working fine i have to redirect it to another page while pressing OK but its not going please help me out
validate & make_sure() function is as like:
function validate() {
if(document.getElementById('cname').value == '')
{
alert('Please enter your name');
document.getElementById('cname').focus();
return false;
}
else if(document.getElementById('address').value == '')
{
alert('Please enter your address');
document.getElementById('address').focus();
return false;
}
else if(document.getElementById('city').value == '')
{
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if(document.getElementById('state').value == '')
{
alert('Please enter your state');
document.getElementById('state').focus();
return false;
}
function make_sure() {
if(confirm("Do you really want to do this?"))
document.forms[0].submit();
else
return false;
}
Use one function for validate and confirm and set action of form to redirect form current page to another page.
function validateAndConfirm() {
if( isEmpty(id('cname').value) ) {
alert('Please enter your name');
id('cname').focus();
return false;
}
else if( isEmpty(id('address').value) ) {
alert('Please enter your address');
id('address').focus();
return false;
}
else if( isEmpty(id('city').value) ) {
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if( isEmpty(id('state').value) ) {
alert('Please enter your state');
id('state').focus();
return false;
} else {
if(confirm("Do you really want to do this?")) {
document.forms[0].submit();
}
else {
return false;
}
}
}
function isEmpty(val){
return (typeof val == 'undefined' || val === undefined || val == null || val.length <= 0) ? true : false;
}
// this function help to simplify you writing : document.getElementById to just id
function id(sid){
return document.getElementById(sid);
}
In my login script when the username and password are both correct it must go to the next page (main/menu page) of the intel XDK.
My problem is how or what code can I use to call the next page whenever the username and password is correct (login successful)?
function validateForm() {
var formUsername = document.forms.login.username.value;
var formPassword = document.forms.login.password.value;
var MINLENGTH = 5;
// Validate username and password
if (formUsername === null || formUsername === "") {
alert("Username must be filled out");
}
else if (formPassword === null || formPassword === "") {
alert("Password must be filled out");
}
else if (formUsername.length < MINLENGTH || formPassword.length < MINLENGTH) {
alert("The minimum length of username and password at least " + MINLENGTH);
}
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
//this is where should i put the code to go at the next page of the XDK API.
return;
}
alert("Login failed!!!");
}
got it guys..
it will be.. like this ..
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
activated_page("#menu");
return;
}
I am trying to use JavaScript to redirect to a PHP page on my site, however, when I do it, nothing happens, apart from the alert boxes if I do not fill in the parameters. Is there something I am doing wrong?
document.getElementById("submit").onclick = check;
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
}
Your default form action takes place overriding your redirect. Return false from the handler to prevent it from taking place:
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
return false; // <------ here
}
What I am looking to do is if a user complete a form it will provide access to a new location.
<script language="JavaScript" type="text/javascript">
<!--
function validateForm(theForm) {
var firstname = theForm.firstname.value;
var lastname = theForm.lastname.value;
var email = theForm.email.value;
if (firstname == "") {
alert("Please fill in your First Name.");
theForm.firstname.focus();
return false;
}
if (lastname == "") {
alert("Please fill in your Last Name.");
theForm.lastname.focus();
return false;
}
if (email == "") {
alert("Please fill in your email address.");
theForm.email.focus();
return false;
}
return true;
}
I know this part is wrong but I have no idea how to go about doing it. any help would be nice..
if lastname=""
if firstname=""
if email=""
load('www.google.com');
if (validateForm(theForm)) window.location = 'http://www.google.com';
Is equivalent to using
if (validateForm(theForm)) window.location.href = 'http://www.google.com';
Both will work, so choose which one you prefer.
if lastname=""
if firstname=""
if email=""
load('www.google.com');
becomes
if ((lastname == "") && (firstname == "") && (email == "")) {
window.location = "http://www.google.com";
}