disable html form submit button using js form verifyer - javascript

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>

Related

javascript validation with email check

when email are already existed, validation is hit the form action redirect the
page.i wanted to if email and all field are right way then hit the action part.
ajax success function not to return properly.
<script language="javascript">
function validate()
{
var str = true;
document.getElementById("msg1").innerHTML = "";
document.getElementById("msg2").innerHTML = "";
document.getElementById("msg3").innerHTML = "";
document.getElementById("msg4").innerHTML = "";
document.getElementById("msg5").innerHTML = "";
document.getElementById("msg6").innerHTML = "";
document.getElementById("msg7").innerHTML = "";
document.getElementById("msg8").innerHTML = "";
document.getElementById("msg9").innerHTML = "";
document.getElementById("msg10").innerHTML = "";
document.getElementById("msg11").innerHTML = "";
if (!document.frm.firstname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.firstname.value.match(patterns))
{
document.getElementById("msg1").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg1").innerHTML = "Please Enter First Name";
str = false;
}
if (!document.frm.lastname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.lastname.value.match(patterns))
{
document.getElementById("msg2").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg2").innerHTML = "Please Enter Last Name";
str = false;
}
if (document.frm.password.value == '')
{
document.getElementById("msg4").innerHTML = "Please Enter Password";
str = false;
}
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!document.frm.phone.value.match(phoneno))
{
document.getElementById("msg5").innerHTML = "Please Enter 10 Digits Mobiles";
str = false;
}
if (document.frm.country.value == '')
{
document.getElementById("msg6").innerHTML = "Please Enter Country";
str = false;
}
if (document.frm.state.value == '')
{
document.getElementById("msg7").innerHTML = "Please Enter State";
str = false;
}
if (document.frm.city.value == '')
{
document.getElementById("msg8").innerHTML = "Please Enter City";
str = false;
}
if (document.frm.address.value == '')
{
document.getElementById("msg9").innerHTML = "Please Enter Address";
str = false;
}
if (document.frm.industry.value == '')
{
document.getElementById("msg10").innerHTML = "Please Select Industry";
str = false;
}
if (document.frm.company.value == '')
{
document.getElementById("msg11").innerHTML = "Please Enter Company Name";
str = false;
}
if (!document.frm.email.value == '')
{
var validate_char = /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\#(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/;
if (!document.frm.email.value.match(validate_char))
{
document.getElementById("msg3").innerHTML = "Please Enter Valid Email ID";
str = false;
} else {
var Email = document.frm.email.value;
var datastring = 'Email=' + Email;
$.ajax({
type: "POST",
url: "client_email.php",
data: datastring,
success: function(responseText) {
if (responseText == 1)
{
$("#msg3").html("Email Is Already Exists");
str = false;
}
}
});
}
} else
{
document.getElementById("msg3").innerHTML = "Email Field Is Empty";
str = false;
}
return str;
}
</script>
Use HTML5's new type attributes to accomplish this..
For email validity write:
<input type="email" name="email" required/>
and if the email is empty or wrong manner ,it will never hit submit event..Hence will not be redirected...
For eg:https://www.w3schools.com/code/tryit.asp?filename=FNZQV8G6AJ8P
for more types:https://www.w3schools.com/html/html_form_input_types.asp
Server Side:
Form Required Every Field By PHP
Form Type Validation By PHP

form validation using javascript,prevent submitting when errors occure

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.

JavaScript validation form integratation into one

I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}

Code which give me error message but not clearing the error message after entering field

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

How to validate multiple fields at the same time using JQuery

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.

Categories