Disable submit button if validation fails - javascript

I want to disable my submit button if all three validation rules below fails otherwise disable false. Any help
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>
Now I want to disable my submit button? How can it be achieved

In that function, initialize a variable, lets say isValid to true.
In the checks, if any check fails, set isValid to false.
And at the bottom of the function, add a condition to enable or disable the Submit button. I'm providing a sample code for your reference.
if (isValid === true) {
// Enable the submit button
}
else {
// Enable the submit button
}

You can add a flag like this:
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
let error = false;
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
if(error){
button.setAttribute('disabled', '')
}else{
button.removeAttribute('disabled')
}
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
error = true;
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
error = true;
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
error = true;
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>

Related

How can we integrate a "valid email" system in this code?

So now I have my successful code. But what I want to do is include this in my AJAX. So this is my AJAX:
function checkEmail() {
// var myForm = $("#mainForm").serialize();
var fname = $("#first").val();
var lname = $("#second").val();
var email = $("#email").val();
var password = $("#password").val();
var repass = $("#en").val();
if (fname && lname && email && password && repass && password.length >= 6 && password == repass)) {
jQuery.ajax({
url: "connection.php",
data: {
fname:fname,
lname:lname,
email:email,
password:password,
repass:repass
},
type: "POST",
success:function(data){
$("#emailExists").show();
$("#email").css("border","2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
if(data){
$("#email").css("border", "2px solid red");
$("#no").css("visibility","visible");
$("#yes").css("visibility","hidden");
}else
{
$("#email").css("border", "2px solid green");
$("#no").css("visibility","hidden");
$("#yes").css("visibility","visible");
window.location.href = 'home.php';
}
$("#emailExists").html(data);
},
error:function (){
}
});
}
}
So, what I want to do, is basically, in that if statement [if(name && lname...)]. In that particular section, I want to include this particular checking if email valid system too. So I was thinking maybe make this code (the if statement to check if email is valid), into a function, to then add it into the AJAX, so something like this:
if (fname && lname && email && password && repass && password.length >= 6 && password == repass && checkValidateEmail()) {
But if I keep that if statement in a function called checkValiateEmail() and do that, it isn't working. What should I do?
Your error is in line 20 (of my snippet, see below). You are passing your email HTMLElement to the validateEmail() function, not the inputs value. The correct code is the following, you had validateEmail(email).
if(email.value === ""){
// ...
}
else if (!validateEmail(email.value)){ // <- the error was here
// ...
}
else{
// ...
}
The full working code is then:
function validateEmail(email) {
const 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,}))$/;
return re.test(email);
}
const email = document.getElementById("email");
const no = document.getElementById("no");
const yes = document.getElementById("yes");
const mailText = document.getElementById("email-text");
const validEmail = document.getElementById("valid");
email.addEventListener("change", function(){
if(email.value === "") {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'visible';
mailText.innerText = "Please enter an email address.";
validEmail.style.visibility = 'hidden';
} else if (!validateEmail(email.value)) {
no.style.visibility = 'visible';
yes.style.visibility = 'hidden';
email.style.border = '2px solid red';
mailText.style.visibility = 'hidden';
validEmail.style.visibility = 'visible';
} else {
yes.style.visibility = 'visible';
no.style.visibility = 'hidden';
email.style.border = '2px solid green';
mailText.style.visibility = 'hidden';
}
});
<input type="text" id="email" />
<span id="yes">Yes</span>
<span id="no">No</span>
<span id="valid">Valid</span>
<p id="email-text"></p>

input validation with two regex

Hi all I have following code: my code
I have 2 inputs and 2 regex for each of them
<input type="text" id="FormField_6_input" placeholder="company name" />
<input type="text" id="FormField_13_input" placeholder="zip code" />
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
I need to check
if company name is valid but zip is not valid then disable button and show error message for zip
if zip code is valid but compony name is not valid then disable button and show error message for company name
if both of them is not valid then then disable button and show both error messages
I write my code only for company name with one regex and it was work very well, for example:
function validat(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const errorMSG = document.getElementById("errorMSG");
if (button && (found || !event.target.value)) {
button.disabled = false;
errorMSG.style.display = "none";
} else {
button.disabled = true;
errorMSG.style.display = "block";
}
}
But when I try to write multi check something going wrong, please help me to resolve this problem.
here is multicheck code:
function validate(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
if (
button &&
(found || !event.target.value) &&
(foundZip || !event.target.value)
) {
if (button && (found || !event.target.value)) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else if (button && (foundZip || !event.target.value)) {
button.disabled = true;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "block";
} else {
button.disabled = false;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "none";
}
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}
}
P.S. please don't change html, only change js.
Thank you.
const checkvalue = (value, regex) => !!value.match(regex);
function validateCompanyName(event, source) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const companyIsCorrect = checkvalue(
companyNameField.value,
companyRGEX
);
const zipIsCorrect = checkvalue(zipPostalCode.value, zipRGEX);
if (button && zipIsCorrect && companyIsCorrect) {
button.disabled = false;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "none";
} else if (button && !zipIsCorrect && companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "none";
} else if (button && zipIsCorrect && !companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}

JavaScript: How can I make this console.log() work?

The third log doesn't go through, does anyone know why??
I've been trying to figure out for a while, and I've been struggling a lot.
var KnowsUsername = true;
var KnowsEmail = true;
var KnowsPassword = true;
setTimeout(function(){
var Username = prompt('What is your username?');
if(Username == '') {
KnowsUsername = true;
console.log("Correct username!");
} else {
KnowsUsername = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong username! try again!');
}
if (KnowsUsername == false) {
return;
} else {
if (KnowsUsername == true) {
var Email = prompt('What is your E-mail?');
if(Email == '') {
KnowsEmail = true;
console.log("Correct E-mail!");
} else {
KnowsEmail = false;
console.error('\x1b[31m%s\x1b[0m', 'Wrong E-mail! try again!');
}
}
if (KnowsEmail == false) {
return;
} else {
if (KnowsEmail == true) {
var Password = prompt('What is your password?');
if (!Password == '') {
KnowsPassword = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong password! try again!');
}
} else {
if(Password == '') {
KnowsPassword = true;
}
console.log("Correct password!");
}
}
}
}, 2100);
The last console.log doesn't work. I've tried changing it a bunch of times, and none of them worked.
Your if-else statement for KnowsEmail == true is incorrect.
I've fixed incorrect statements and also removed unnecessary satements.
var KnowsUsername = true;
var KnowsEmail = true;
var KnowsPassword = true;
setTimeout(function () {
var Username = prompt('What is your username?');
if (Username == '') {
KnowsUsername = true;
console.log('Correct username!');
var Email = prompt('What is your E-mail?');
if (Email == '') {
KnowsEmail = true;
console.log('Correct E-mail!');
var Password = prompt('What is your password?');
if (Password == '') {
KnowsPassword = true;
console.log('Correct password!');
} else {
KnowsPassword = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong password! try again!');
}
} else {
KnowsEmail = false;
console.error('\x1b[31m%s\x1b[0m', 'Wrong E-mail! try again!');
}
} else {
KnowsUsername = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong username! try again!');
}
}, 2100);

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

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

Categories