I am going to create simple validation form using Vanilla JavaScript, but I have problem, I want to check first ('entername') field, if user will not enter any letters in it, i want to console log message ('enter name'), it's works fine, but after that user reenter his name if field it returns in console ('enter name'), i want to return ('not enter') message.
var userBtn = document.getElementById('checkuserinputs');
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
userBtn.addEventListener('click', function(){
if(checkUserName.length == 0){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to get the value after clicking the button. If you put it outside of the click event, the value will never be updated.
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function () {
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if (checkUserName.length == 0) {
console.log('enter name')
} else {
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername" />
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname" />
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber" />
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to retrieve the value of the input field in the click function callback:
userBtn.addEventListener('click', () => {
const checkUserName = document.getElementById('user-name').value;
if(checkUserName.length === 0){
console.log('enter name')
} else {
console.log('not enter')
}
})
change the variable geting value to button click function that is,
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
Related
document.querySelector('.login').addEventListener('click', function() {
const check = document.querySelector('.username').value;
console.log(typeof check);
if (!check) {
document.querySelector('.errorMessage').textContent =
'kindly enter your username';
}
});
<div class="user-login">
<form>
<label for="">User Name : <input type="text" name="userName" class=" username"></label> <br>
<label for="">Password: <input type="password" name="" class="password"></label> <br>
<button class="login">Login</button>
</form>
</div>
<div class="errorMessage">
<label for=""></label> <br>
</div>
To your html modify the button like this:
<button type="button" class="login">Login</button>
or in your javascript you can do something like this:
document.querySelector('.login').addEventListener('click', function(e) {
e.preventDefault(); // Add this after set 'e' as parameter
const check = document.querySelector('.username').value;
console.log(typeof check);
if (!check) {
document.querySelector('.errorMessage').textContent =
'kindly enter your username';
}
});
So basically, I'm trying to do client side validation through JavaScript, but the code does not seem to be working. I am not getting any alert box. Below is HTML Form and JavaScript. I have skipped html and Body tags for obvious reasons. Can someone look over and see where am I making a mistake?
HTML form
<div class="container" >
<h1 style="text-align: center;">Online Vaccine Registration Form</h1>
<h1 style="text-align: center;">Developed by yourname</h1>
<form method="post" name="vacform" onsubmit=" return validateForm()">
<table>
<div class="row">
<div class="form-group col-md-6">
<label for="Name">Name : </label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group col-md-6">
<label for="CNIC" >CNIC : </label>
<input type="text" class="form-control" name="CNIC" placeholder="CNIC">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="Mob">Mobile : </label>
<input type="number" class="form-control" name="Mob" placeholder="Mobile">
</div>
<div class="form-group col-md-6">
<label for="Dob" >DoB : </label>
<input type="date" class="form-control" name="DoB">
</div>
</div>
<div class="form-group">
<label for="cen">Nearby centre</label>
<select class="form-control" id="sel1">
<option selected disabled>Select your Nearest Centre</option>
<option>Karachi West</option>
<option>Karachi East</option>
<option>Karachi North</option>
<option>Karachi Central</option>
<option>Malir</option>
</select>
</div>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript
function validateForm()
{
var varname = document.vacform.name.value;
var varcnic = document.vacform.CNIC.value;
var varMob = document.vacform.Mob.value;
var varDoB = new Date(DoB);
var limitdate = new Date('2010-01-01');
var CNlength = 13;
var num = /^[0-9]+$/;
var str = /^[A-Za-z]+$/;
if(document.vacform.name.value!="")
{
if(document.vacform.CNIC.value!="")
{
if(document.vacform.Mob.value!="")
{
if(document.vacform.DoB.value!="")
{
if(varname.match(str))
{
if(varcnic.lenght == CNlength)
{
if(varcnic.match(num))
{
if(varDoB.getYear() < limitdate.getYear())
{
alert("All types of Validations have been done")
return true;
}
else
{
alert("Date should be less than 01-01-2010")
return false;
}
}
else
{
alert("CNIC field should have numbers only")
return false;
}
}
else
{
alert("CNIC lenght should be 13")
return false;
}
}
else
{
alert("Name can only contain letters")
return false;
}
}
else
{
alert("Date of Birth must be entered")
return false;
}
}
else
{
alert("Please Enter your mobile number")
return false;
}
}
else
{
alert("CNIC number Required")
return false;
}
}
else
{
alert("Name field can not be empty")
return false;
}
}
</script>
You call the function from the onsubmit event handler, however you never submit the form so it can't be triggered.
<button type="button" class="btn btn-primary">Submit</button>
This kind of button is for hooking JS into. It isn't a submit button.
Set type="submit" or remove the type attribute entirely (submit is the default).
Also address the errors in your HTML that a validator would highlight.
good evening.
I'm a beginner with JavaScript and I'm trying to recreate a specific webpage. There, exists a button that, if the login form doesn't have at least 11 elements on user and 8 on password, the button is disabled.
How can I do this with HTML and JS?
function blockButtonByUser() {
var cpfleng = document.getElementById('.iptuser').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
function blockButtonByPassword() {
var passwordlength = document.getElementById('.iptpassword').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit'>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
Thanks for the help!
Here is something like that using an eventListener:
var cpfOkay = false
var passwordOkay = false;
var btnsubmit = document.getElementsByClassName('btnsubmit')[0];
document.getElementById('cpf').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
cpfOkay = false;
if (event.target.value.length >= 11) {
cpfOkay = true;
}
checkBoth();
})
document.getElementById('password').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
passwordOkay = false;
if (event.target.value.length >= 8) {
passwordOkay = true;
}
checkBoth();
})
function checkBoth() {
btnsubmit.disabled = true;
btnsubmit.style.opacity = 0.5;
if (cpfOkay && passwordOkay) {
btnsubmit.disabled = false;
btnsubmit.style.opacity = 1;
}
}
<header><img src="https://placekitten.com/200/300" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' disabled style="opacity:0.5">
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
You can add event listeners for input event for both the user and password, and based on requirements you can enable or disable the button. You can refactor your code like this:
var cpf = document.getElementById('cpf')
var password = document.getElementById('password')
var btnsubmit = document.getElementById('btnsubmit')
cpf.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
password.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' id='btnsubmit' disabled>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
<script src="main.js"></script>
You have a few issues. One was getElementById on classes. One was no event handler. Lastly, you were trying to get the length on the element, but not the length of the value.
This should work:
document.querySelector('.btnsubmit').addEventListener('click', e =>{
blockButtonByUser();
blockButtonByPassword()
})
function blockButtonByUser(){
var cpfleng = document.querySelector('.iptuser').value.length
console.log(cpfleng)
var btnsubmit = document.querySelector('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
function blockButtonByPassword(){
var passwordlength = document.querySelector('.iptpassword').value.length
console.log(passwordlength)
var btnsubmit = document.querySelector('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
Working on form validation i'am trying to hide submit button until all text and password fields are not null and satisfies all input validation, but the problem is, it is enabling the submit button for the first text field validation only.
So what's wrong with my code, please correct me.,
Here's the code:
$(document).ready(function() {
var error_firstName = false;
var error_lastName = false;
var error_emailAdd = false;
var error_pass = false;
var error_confirmPass = false;
var error_mobile = false;
var error_confirmMob = false;
$("#error_form_firstName").hide();
$("#error_form_lastName").hide();
$("#error_form_emailAdd").hide();
$("#error_form_password").hide();
$("#error_span").hide();
$("#error_form_confirmPassword").hide();
$("#error_form_mobile").hide();
$("error_form_confirmNumber").hide();
$("#formSubmit").attr("disabled", "disabled");
$("#form_firstName").focusout(function() {
check_FirstName();
});
$("#form_lastName").focusout(function() {
check_LastName();
});
$("#form_email").focusout(function() {
check_email();
});
$("#form_pass").focusout(function() {
check_password();
});
$("#form_cPass").focusout(function() {
check_confirm_password();
});
$("#form_mob").focusout(function() {
check_Mobile();
});
$("#form_cMob").focusout(function() {
check_cMobile();
});
$('input, password').change(function(){
if(error_firstName == false && error_lastName == false && error_emailAdd == false && error_pass == false && error_confirmPass == false && error_mobile == false && error_confirmMob == false){
$("input[type=submit]").removeAttr("disabled");
return true;
}
else{
alert("Please fill the form correctly");
return false;
}
});
});
Corresponding HTML code for form validation:
<form:form id="reg_form" action="submitRegistration.do" method="POST"
commandName="registrationForm">
<div class="col-md-6 col-md-offset-3 register-top-grid">
<h3>Please fill the below information</h3>
<div>
<span>First Name</span>
<form:input id="form_firstName" path="firstName" />
<form:errors path="firstName" cssStyle="color:red" element="div" />
<p id="error_form_firstName" class="errorMessage"></p>
</div>
<div>
<span>Last Name</span>
<form:input id="form_lastName" path="lastName" />
<form:errors path="lastName" cssStyle="color:red" element="div" />
<p id="error_form_lastName" class="errorMessage"></p>
</div>
<div>
<span>Email Address</span>
<form:input id="form_email" path="email" />
<form:errors path="email" cssStyle="color:red" element="div" />
<p id="error_form_emailAdd" class="errorMessage"></p>
</div>
<div>
<span>Password</span>
<form:password id="form_pass" path="password" />
<form:errors path="password" cssStyle="color:red" element="div" />
<p id="error_form_password" class="errorMessage"></p>
<!-- This is for extra line after password for alignment of error_text -->
<p id="error_span" class="errorMessage"></p>
</div>
<div>
<span>Confirm Password</span>
<form:password id="form_cPass" path="confirmPassword" />
<form:errors path="confirmPassword" cssStyle="color:red" element="div" />
<p id="error_form_confirmPassword" class="errorMessage"></p>
</div>
<div>
<span>Mobile Number</span>
<form:input id="form_mob" path="mobile" />
<form:errors path="mobile" cssStyle="color:red" element="div" />
<p id="error_form_mobile" class="errorMessage"></p>
</div>
<div>
<span>Confirm Mobile Number</span>
<form:input id="form_cMob" path="confirmMobile" />
<form:errors path="confirmMobile" cssStyle="color:red" element="div" />
<p id="error_form_confirmNumber" class="errorMessage"></p>
</div>
<div style="text-align: center">
<input id="formSubmit" type="submit" value="submit" /> <button id="clear" type="button" value="clear" />
</div>
<a class="news-letter" href="#"> <label class="checkbox">
<input type="checkbox" name="checkbox" checked=""><i> </i>Sign Up for Newsletter</label>
</a>
</div>
<div class="clearfix"></div>
</form:form>
IF I am reading this correctly, you have a function for each input to check THAT ONE INPUT when you focus out. Now assume you have First Name and it is OK after entry - your 'Last Name' has not yet been entered/checked; yet you have negative errors (all set false) by default. I would suggest to set them all to true instead - so that they are all entered before the submit gets enabled. I make assumption that all elements are required.
Optionally, on one "focusout", trigger that focusout event on ALL of them, but that is a good bit of extra code on each focus out.
Another option would be to have a "validateform" function and use that for all of them i.e.
var error_firstName = true;
var error_lastName = true;
var error_emailAdd = true;
var error_pass = true;
var error_confirmPass = true;
var error_mobile = true;
var error_confirmMob = true;
function validateform(){
check_FirstName();
check_LastName();
check_email();
// the others in here...
// now do this
var hasErrors = error_firstName
|| error_lastName
|| error_emailAdd
|| error_pass
|| error_confirmPass
|| error_mobile
|| error_confirmMob;
if(hasErrors){alert("Please fill the form correctly");}
$("#formSubmit").prop("disabled", hasErrors");
return hasErrors;
}
// add others in here
$("#form_firstName,#form_lastName,#form_email")
.on("focusout change",validateform);
Note you could also do a bulk show/hide of your error things like this:
function displayErrorThings(){
$("#error_form_firstName").toggle(error_firstName);
$("#error_form_lastName").toggle(error_lastName);
$("#error_form_emailAdd").toggle(error_emailAdd);
$("#error_form_password").toggle(error_pass);
$("#error_span").toggle(error_pass);
$("#error_form_confirmPassword").toggle(error_confirmPass);
$("#error_form_mobile").toggle(error_mobile);
$("error_form_confirmNumber").toggle(error_confirmMob);
}
Thus just call it in the same validation function above (and on initial start)
displayErrorThings()
I try to validate user's input from client side using JavaScript but it not work.
First I write a validation in JavaScript file like this:
var main = function checkLomake() {
try {
var etu = $("#etu").val();
var suku = $("#suku").val();
var sposti = $("#sposti").val();
var puh = $("#puhelin").val();
var osoite = $("#osoite").val();
var etuVirhe = checkNimi(etu);
var sukuVirhe = checkNimi(suku);
var spostiVirhe = checkSposti(sposti);
var puhVirhe = checkPuh(puh);
var osoiteVirhe = checkOsoite(osoite);
if (etuVirhe === 1 && sukuVirhe === 1 && spostiVirhe === 1 && puhVirhe === 1 && osoiteVirhe === 1)
alert(getVirhe(1));
return false;
else {
if (etuVirhe !== 0) {
alert(getVirhe(checkNimi(etu)));
}
if (sukuVirhe !== 0) {
alert(getVirhe(checkNimi(suku)));
}
if (osoiteVirhe !== 0) {
alert(getVirhe(checkOsoite(osoite)));
}
if (puhVirhe !== 0) {
alert(getVirhe(checkPuh(puh)));
}
if (spostiVirhe !== 0) {
alert(getVirhe(checkSposti(sposti)));
}
return false;
}
} catch (e) {
}
};
Then I call it when user submit a form like this:
$(document).ready(function () {
$("#form-lomake").on("submit",function () {
return main();
});
});
And in HTML file I have a form like this:
<form id="form-lomake" name="form-lomake" action="uusivaraus.php" method="post">
<div data-role="collapsible" data-collapsed-icon="carat-r" data-expanded-icon="carat-d" id="coll-lomake">
<h1>Täytä tiedot</h1>
<div class="ui-field-contain">
<label for="etu">Etunimi</label>
<input type="text" id="etu" placeholder="etunimi" name="etu" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($nimiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="suku">Sukunimi</label>
<input type="text" id="suku" placeholder="sukunimi" name="suku" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($nimiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="osoite">Osoite</label>
<input type="text" id="osoite" placeholder="osoite" name="osoite" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($osoiteVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="sposti">Email</label>
<input type="text" id="sposti" placeholder="sähköposti" name="sposti" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($spostiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="puhelin">Puhelin</label>
<input type="text" id="puhelin" placeholder="puhelin numero" name="puhelin" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($puhVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<textarea rows="10" cols="10" placeholder="lisätietoja" name="lisatieto"></textarea>
</div>
<div class="ui-grid-b">
<div class="ui-block-a">
<input type="reset" value="Peruu" id="btn-peruuta" name="peruuta" class="ui-btn ui-corner-all ui-shadow" data-icon="delete" />
</div>
<div class="ui-block-b"></div>
<div class="ui-block-c">
<input type="submit" value="Varaa" id="btn-varaa" name="varaa" class="ui-btn ui-corner-all ui-shadow ui-btn-active" data-icon="check" data-iconpos="right" />
</div>
</div>
</div>
</form>
But I don't know why when I submit a form, it go straight to PHP file without checking user's input. Can someone help me for resolving this issue, thanks.
You are not preventing the form from being submitted, and as the form action attribute is action="uusivaraus.php", you are being redirected to the .php file when it submits. You need to prevent the default form submission before calling your function:
$(document).ready(function () {
$("#form-lomake").on("submit",function (e) {
e.preventDefault(); //this will prevent the default submission
return main();
});
Here is a working example.