I'm trying to apply form validation using js,the problem I'm facing is the form always submits no matter what errors are shown in the form.
the form contains 6 fields: username,email,password,retype_pass, first_name,last_name.
the js code is like this:
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
Download the js file here : https://onionfiles.com/file/HGGaFR2G
and include it in, then try this
$().ready(function() {
// validate form on keyup and submit
$("#FORMID").validate({
rules: {
username: "required",
email: "required",
password: "required",
retype_pass: {
required: true,
equalTo:"#password"
}
first_name: "required",
last_name: "required"
},
messages: {
username: "Please enter Username",
email : "Please enter a valid Email",
password: "Please enter a password",
retype_pass: {
required: "Please confirm your password",
equalTo: "Please enter the same password as above"
},
first_name: "Please enter first name",
last_name: "Please enter last name"
}
});
});
A quick fix from your code will be the following.
(function() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
$("#formId").on("submit", checkForBlank);
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
username_err = false;
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
//var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
var re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
pwd_err_msg = false;
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2 || pass2.length === 0) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
confirm_pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
confirm_pwd_err_msg = false;
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
email_err = false;
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
fname_err = false;
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
lname_err = false;
}
}
}
function checkForBlank(e) {
check_userName();
check_email();
check_pwd();
check_pwd_conf();
check_fname();
check_lname();
if(username_err || email_err || pwd_err_msg || confirm_pwd_err_msg || fname_err || lname_err) {
e.preventDefault();
}
}
}());
I have changed the checkForBlank function. I have attached it to the form submit event and checked for any errors inside it. Then prevented form submission if any errors found.
But I think the whole code needs to be refactored to reduce code duplication.
Update:
I have made changes to the above code. Here is the working jsfiddle.
Related
I am trying to make a simple js form verifier using boolean values which checks if the inputs from html are correct and enables the submit button if fields are correct or disables it if not. It disables the submit button but when data is entered correctly it does not re enable the submit button.
var validemail = false ;
var validpassword = false ;
var validusername = false ;
var validage = false ;
function verifyemail()
{
var email = document.getElementById("signupemail").value ;
var error = document.getElementById("signupemailerrors") ;
var emailregex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;
if(email.length < 254){
if( email.length > 0 ){
if(email.match(emailregex)){
error.innerHTML = "";
validemail = true ;
}
else
{
error.innerHTML = "Invalid email address.";
validemail = false ;
}
}else
{
error.innerHTML = "Please fill in." ;
validemail = false ;
}
} else
{
error.innerHTML = "Maximum length exceeded.";
validemail= false ;
}
}
function verifypassword(){
var password = document.getElementById("signuppassword").value;
var passworderror= document.getElementById("signuppassworderrors") ;
if (password.length < 254){
if(password.length > 7){
passworderror.innerHTML = "";
validpassword = true ;
}
else if(password.length == 0)
{
passworderror.innerHTML = "Please fill in.";
validpassword = false ;
}
else
{
passworderror.innerHTML = "At least 8 characters required.";
validpassword = false ;
}
}
else
{
passworderror.innerHTML = "Maximum length exceeded.";
validpassword = false ;
}
}
function verifyusername(){
var username = document.getElementById("signupusername").value ;
var usernamerror = document.getElementById("signupusernameerrors") ;
if (username.length == 0)
{
usernamerror.innerHTML = "Please fill in.";
validusername = false;
}
else if (username.length > 50)
{
usernamerror.innerHTML = "Maximum length exceeded.";
validusername = false;
}
else
{
usernamerror.innerHTML = "";
validusername = true;
}
}
function verifyage(){
var age = document.getElementById("signupage").value ;
var ageerror = document.getElementById("signupageerrors") ;
var ageregex = /^\d+$/;
if(age.length == 0){
ageerror.innerHTML = "Please fill this field";
validage = false;
}
else
{
if (age.match(ageregex)){
if (age == 0){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
}
else if(age > 130){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
}
else
{
ageerror.innerHTML = "" ;
validage = true;
}
}else
{
ageerror.innerHTML = "Only numbers allowed."
validage = false;
}
}
}
function verifysubmit(){
verifyage();
verifyemail();
verifypassword();
verifyusername();
if (validage == true && validemail == true && validpassword == true && validusername == true)
{
document.getElementById("signupformsubmit").disabled = false ;
}
else{
document.getElementById("signupformsubmit").disabled = true ;
}
}
UPDATE tested and worked code:
<input type="text" id="signupemail" oninput="verifyemail();">
<div id="signupemailerrors"></div>
<input type="password" id="signuppassword" oninput="verifypassword();">
<div id="signuppassworderrors"></div>
<input type="text" id="signupage" oninput="verifyage();">
<div id="signupageerrors"></div>
<input type="text" id="signupusername" oninput="verifyusername();">
<div id="signupusernameerrors"></div>
<input type="submit" id="signupformsubmit">
<script>
var validemail = false ;
var validpassword = false ;
var validusername = false ;
var validage = false ;
verifysubmit();
function verifyemail(){
var email = document.getElementById("signupemail").value;
var emailerror = document.getElementById("signupemailerrors");
var emailregex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
validemail = true;
emailerror.innerHTML = "";
if (email.length == 0) {
emailerror.innerHTML = "Please fill in." ;
validemail = false ;
} else if (email.length > 254) {
emailerror.innerHTML = "Maximum length exceeded.";
validemail= false ;
} else if (!email.match(emailregex)) {
emailerror.innerHTML = "Invalid email address.";
validemail = false ;
}
verifysubmit();
}
function verifypassword(){
var password = document.getElementById("signuppassword").value;
var passworderror= document.getElementById("signuppassworderrors") ;
validpassword = true;
passworderror.innerHTML = "";
if (password.length == 0) {
passworderror.innerHTML = "Please fill in." ;
validpassword = false ;
} else if (password.length < 8) {
passworderror.innerHTML = "At least 8 characters required.";
validpassword= false ;
} else if (password.length > 254) {
passworderror.innerHTML = "Maximum length exceeded.";
validpassword= false ;
}
verifysubmit();
}
function verifyusername(){
var username = document.getElementById("signupusername").value;
var usernamerror= document.getElementById("signupusernameerrors") ;
validusername = true;
usernamerror.innerHTML = "";
if (username.length == 0) {
usernamerror.innerHTML = "Please fill in." ;
validusername = false ;
} else if (username.length < 3) {
usernamerror.innerHTML = "At least 3 characters required.";
validusername= false ;
} else if (username.length > 50) {
usernamerror.innerHTML = "Maximum length exceeded.";
validusername= false ;
}
verifysubmit();
}
function verifyage(){
var age = document.getElementById("signupage").value ;
var ageerror = document.getElementById("signupageerrors") ;
var ageregex = /^\d+$/;
validage = true;
ageerror.innerHTML = "";
if (age.length == 0){
ageerror.innerHTML = "Please fill this field";
validage = false;
} else if ((age > 130) || (age == 0)) {
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
} else if (!age.match(ageregex)) {
ageerror.innerHTML = "Only numbers allowed."
validage = false;
}
verifysubmit();
}
function verifysubmit() {
if (!validage || !validemail || !validpassword || !validusername)
document.getElementById("signupformsubmit").disabled = true;
else
document.getElementById("signupformsubmit").disabled = false;
console.log(validage + " " + validemail + " " + validpassword + " " + validusername);
}
</script>
I managed to solve the problem. Solved link jsfiddle. If you can think of a simpler way to fix this, please comment. Thank you very much for your help.
var validemail = false ;
var validpassword = false ;
var validusername = false ;
var validage = false ;
function verifyemail()
{
var email = document.getElementById("signupemail").value ;
var error = document.getElementById("signupemailerrors") ;
var emailregex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;
if(email.length < 254){
if( email.length > 0 ){
if(email.match(emailregex)){
error.innerHTML = "";
validemail = true ;
verifysubmit();
}
else
{
error.innerHTML = "Invalid email address.";
validemail = false ;
verifysubmit();
}
}else
{
error.innerHTML = "Please fill in." ;
validemail = false ;
verifysubmit();
}
} else
{
error.innerHTML = "Maximum length exceeded.";
validemail= false ;
verifysubmit();
}
}
function verifypassword(){
var password = document.getElementById("signuppassword").value;
var passworderror= document.getElementById("signuppassworderrors") ;
if (password.length < 254){
if(password.length > 7){
passworderror.innerHTML = "";
validpassword = true ;
verifysubmit();
}
else if(password.length == 0)
{
passworderror.innerHTML = "Please fill in.";
validpassword = false ;
verifysubmit();
}
else
{
passworderror.innerHTML = "At least 8 characters required.";
validpassword = false ;
verifysubmit();
}
}
else
{
passworderror.innerHTML = "Maximum length exceeded.";
validpassword = false ;
verifysubmit();
}
}
function verifyusername(){
var username = document.getElementById("signupusername").value ;
var usernamerror = document.getElementById("signupusernameerrors") ;
if (username.length == 0)
{
usernamerror.innerHTML = "Please fill in.";
validusername = false;
verifysubmit();
}
else if (username.length > 50)
{
usernamerror.innerHTML = "Maximum length exceeded.";
validusername = false;
verifysubmit();
}
else
{
usernamerror.innerHTML = "";
validusername = true;
verifysubmit();
}
}
function verifyage(){
var age = document.getElementById("signupage").value ;
var ageerror = document.getElementById("signupageerrors") ;
var ageregex = /^\d+$/;
if(age.length == 0){
ageerror.innerHTML = "Please fill this field";
validage = false;
verifysubmit();
}
else
{
if (age.match(ageregex)){
if (age == 0){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
verifysubmit();
}
else if(age > 130){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
verifysubmit();
}
else
{
ageerror.innerHTML = "" ;
validage = true;
verifysubmit();
}
}else
{
ageerror.innerHTML = "Only numbers allowed."
validage = false;
verifysubmit();
}
}
}
function verifysubmit(){
if (validage == true && validemail == true && validpassword == true && validusername == true)
{
document.getElementById("signupformsubmit").disabled = false ;
}
else{
document.getElementById("signupformsubmit").disabled = true ;
}
}
Make sure that you are using "onChange" listener on each field.
<input type="text" id="signupemail" onchange="verifysubmit()">
<input type="password" id="signuppassword" onchange="verifysubmit()">
<input type="text" id="signupusername" onchange="verifysubmit()">
<input type="text" id="signupage" onchange="verifysubmit()">
So the onChange will perform the checker on each change and if the checkers are ok you submit button will be re-enabled
You can give a class to all input field which you want to check validation. and for that class you can create on blur method and call verifysubmit() method. "AND I THING YOU HAVE TO RETURN A VALUE WHICH YOU ARE STORING VARIABLE TRUE OR FALSE" store that function out put in variable and check that variable in if condition where you are enable and disable a button.
<script>
$(".errorField").on("blur",function(e){
verifysubmit();
})
</script>
<input type="text" id="signupemail" class="errorField">
<input type="password" id="signuppassword" class="errorField">
Modify your code try it.
<!DOCTYPE html>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function(){
$("#signupformsubmit").on("click",function(e){
e.preventDefault();
verifysubmit();
});
$(".errorField").on("blur",function(e){
verifysubmit();
})
var validemail = false ;
var validpassword = false ;
var validusername = false ;
var validage = false ;
function verifyemail()
{
var email = document.getElementById("signupemail").value ;
var error = document.getElementById("signupemailerrors") ;
var emailregex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;
if(email.length < 254){
if( email.length > 0 ){
if(email.match(emailregex)){
error.innerHTML = "";
console.log("preg");
return validemail = true ;
}
else
{
error.innerHTML = "Invalid email address.";
return validemail = false ;
}
}else
{
error.innerHTML = "Please fill in." ;
return validemail = false ;
}
} else
{
error.innerHTML = "Maximum length exceeded.";
return validemail= false ;
}
}
function verifypassword(){
var password = document.getElementById("signuppassword").value;
var passworderror= document.getElementById("signuppassworderrors") ;
if (password.length < 254){
if(password.length > 7){
passworderror.innerHTML = "";
return validpassword = true ;
}
else if(password.length == 0)
{
passworderror.innerHTML = "Please fill in.";
return validpassword = false ;
}
else
{
passworderror.innerHTML = "At least 8 characters required.";
return validpassword = false ;
}
}
else
{
passworderror.innerHTML = "Maximum length exceeded.";
return validpassword = false ;
}
}
function verifyusername(){
var username = document.getElementById("signupusername").value ;
var usernamerror = document.getElementById("signupusernameerrors") ;
if (username.length == 0)
{
usernamerror.innerHTML = "Please fill in.";
validusername = false;
}
else if (username.length > 50)
{
usernamerror.innerHTML = "Maximum length exceeded.";
validusername = false;
}
else
{
usernamerror.innerHTML = "";
validusername = true;
}
}
function verifyage(){
var age = document.getElementById("signupage").value ;
var ageerror = document.getElementById("signupageerrors") ;
var ageregex = /^\d+$/;
if(age.length == 0){
ageerror.innerHTML = "Please fill this field";
validage = false;
}
else
{
if (age.match(ageregex)){
if (age == 0){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
}
else if(age > 130){
ageerror.innerHTML = "Please provide your real age." ;
validage = false;
}
else
{
ageerror.innerHTML = "" ;
validage = true;
}
}else
{
ageerror.innerHTML = "Only numbers allowed."
validage = false;
}
}
}
function verifysubmit(){
console.log("test");
//verifyage();
var email = verifyemail();
var pass = verifypassword();
console.log(email+pass);
// verifyusername();
if (email == 1 && pass == 1)
{
console.log("true");
document.getElementById("signupformsubmit").disabled = false ;
}
else{
document.getElementById("signupformsubmit").disabled = true ;
}
}
});
</script>
<input type="text" id="signupemail" class="errorField">
<input type="password" id="signuppassword" class="errorField">
<input type="button" id="signupformsubmit" value="Submit" >
<div id="signupemailerrors"></div>
<div id="signuppassworderrors"></div>
</html>
Code which give me error message but not clearing the error message after entering field :
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
}
function check(form) {
flag = 0;
otpValidate();
if (flag == 1)
return false;
else
return true;
}
Just add an empty message in your main function. Then call a keyup function to call your main function. try something like:
function otpValidate() {
var otp = oneTimePass.onetimepass.value.trim();
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
var otp = oneTimePass.onetimepass;
otp.addEventListener("keyup", otpValidate);
Optimized way
function otpValidate() {
otp = oneTimePass.onetimepass.value.trim();
document.getElementById('error0').innerHTML = "";
flag = 0;
if(!otp) {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
return flag;
}
function check(form) {
var flag = otpValidate();
if (flag == 1)
return false;
return true;
}
First of all fix the codes here
function check(form) {
//flag = 0; This will make no sense to check it
otpValidate();
if (flag == 1)
{
flag = 0;
return false;
}
else
return true;
}
And for the problem you are facing
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
}
}
Try like this
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
function check(form) {
otpValidate();
if (flag == 1)
return false;
else
return true;
}
I am facing issue with javascript for form validation.
On one of the forms the javascript function is working properly, and when on other form, i am trying to do form validation, but the script does not fire up.. i have tried many times to clear my browser cache and refreshed the page but i am not getting any results.
I would be thankful if anyone reviews it and help spot the issue.
The following is the function that works on my homepage:
<script>
function validate()
{
var uid = document.getElementById("usrname").value;
var pwd = document.getElementById("passwd").value;
if (uid == "" || pwd == "") {
alert("Empty fields not allowed");
return false;
}
else if (uid.length < 4 || uid.length > 20) {
alert("User ID string length should be between 4 - 20");
return false;
}
else if (pwd.length < 6 || pwd.length >20) {
alert("Password length should be between 6 - 20");
return false;
}
return true;
}
</script>
<form name="ulogin" action="login.php" method="post" onSubmit="return validate();">
The following validation code on the other page does not run:
<script>
function regval()
{
var cname = document.getElementById("name1").value;
var email = document.getElementById("email").value;
var phn = document.getElementById("phone").value;
var addr1 = document.getElementById("addr1").value;
var addr2 = document.getElementById("addr2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var uname = document.getElementById("uname").value;
var pwd = document.getElementById("passwd").value;
var cnfp = document.getElementById("cnf_passwd").value;
var secans = document.getElementById("sec_ans").value;
var regex=/^[0-9]+$/;
var alphanum=/^[a-z0-9]+$/i;
if(cname == "" || email == "" || phn == "" || addr1 == "" || addr2 == "" || city == "" || state == "" || state == "" || country == "" || uname == "" || pwd == "" || cnfp == ""|| secans == "") {
alert("Empty fields not allowed");
return false;
}
if (cname.length < 3 || cname.length > 20) {
alert("Name length should be between 4-20 characters.");
return false;
}
if (email.length < 10 || email.length > 50 ) {
alert("email length should be between 10-50 characters.");
return false;
}
if (phn.length < 7 || phn.length > 11 ) {
alert("check phone number length.");
return false;
}
else if (!phn.match(regex)) {
alert("Please check inputs, only numbers are allowed.!");
return false;
}
if (city.toLowerCase() != "surat" || state.toLowerCase() != "gujarat" || country.toLowerCase() != "india") {
alert("Sorry, we only serve in surat currently at the moment..!!");
return false;
}
if (uname.length < 4 || uname.length > 20) {
alert("user name should be between 4 - 20 characters.");
return false;
}
else if (!uname.match(alphanum)) {
alert("only characters A-z 0-9 are allowed.");
return false
}
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
if (pwd != cnfp) {
alert("the passwords do not match, please check and try again.");
return false;
}
if (secans.length < 5 || secans.length > 20) {
alert("please check for security answer length. It should be between 5 to 20 characters.");
return false;
}
return true;
}
</script>
<form name="usreg" action="signup.php" method="POST" onSubmit="return regval();">
the script tags are in the head tags of my webpage.
Thanks in advance.
Missing closing bracket ) Here else if (!pwd.match(alphanum) {
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Should be
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum)) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Note: Always check browser console log for errors.
I have some javascript written to validate that a string is alphanumeric but i was just wondering how i could add some code to include hyphens(-) and slash's(/) as acceptable inputs. Here is my current code:
function validateAddress() {
var address = document.getElementById('address');
if (address.value == "") {
alert("Address must be filled out");
return false;
} else if (document.getElementById('address').value.length > 150) {
alert("Address cannot be more than 150 characters");
return false;
} else if (/[^a-zA-Z0-9\-\/]/.test(address)) {
alert('Address can only contain alphanumeric characters, hyphens(-) and back slashs(\)');
return false;
}
}
Simply add them to the character group. Of course, because both - and / are special characters in this context (/ ends a RegExp, - expresses a range), you'll need to escape them with a preceding \:
function validateAddress(){
var TCode = document.getElementById('address').value;
if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
function isValidCharacter(txtTitle) {
var title = document.getElementById(txtTitle);
var regExp = /^[a-zA-Z]*$/
if (!regExp.test(title.value)) {
title.value = '';
return false;
}
else {
return true;
}
}
function Validation(){
var txtTitles = document.getElementById('txtTitle');
if (isValidCharacter(txtTitles.id) == false) {
alert("Please enter valid title. No special character allowed.");
return false;
}
}
$("#Btn").unbind("click").click(function () {
if (Validation() == false) {
}
else {
//success
}
}
Input:
<input type="text" name="textname" id="tname" onblur="namefun(this.value)">
Javascript
function namefun(c) {
var spch = /[A-z\s]/gi;
var dig = /[0-9]/g;
var ln = c.length;
var j = 1;
for (var i = 0; i < ln; i++) {
var k = c.slice(i, j);
if (spch.test(c) == false || dig.test(c) == true) {
alert("Invalid name");
document.getElementById("tname").value = "";
ln = 0;
setTimeout(function () {
tname.focus();
}, 1);
//return false;
}
j++;
}
}
Simple Javascript Version
isValidCharacter(text) {
const validCharacterRegex = /^[a-zA-Z]*$/;
return validCharacterRegex.test(text);
}
Typescript Version
isValidCharacter(text: string): boolean {
const validCharacterRegex: RegExp = /^[a-zA-Z]*$/;
return validCharacterRegex.test(text);
}
<?php
if(isset($_POST["Password"]))
{
$servername="localhost";
$username="root";
$password="";
$dbname="coustomer";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("connection failed:" .mysqli_connect_error());
}
$UserID= $_POST["Userid"];
$Password= $_POST["Password"];
$sql= "SELECT Name, Contact, Email, UserID, Password FROM coustomers WHERE UserID ='$UserID' password='$Password' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo '<script>alert("Login successfully")</script>';
}
{
else
{
echo "No record found";
}
}
?>
I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.