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('');
Related
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
}
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)
}
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;
}
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";
}
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.