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';
}
});
Related
I have a bootstrap form. I want to do validation on this form with pattern for example only alphabet regex for name field
My form validation does not work. where is problem?
const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value;
const ptern = /^[A-Za-z]+$/;
isPasswordValid = ptern.test(en);
(() => {
'use strict'
const forms = document.querySelectorAll('.needs-validation');
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity() || !isPasswordValid) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
<form id="Oform" action="" class="form-control needs-validation" novalidate>
<label for=" OName">name</label>
<input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
<div class="input-group form-control">
<label class="col-sm-12" for="IPrange"> family</label>
<input required class="form-control" type="text" name="" id="IPrange">
</div>
<button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>
You need to move the validation into the submit event.
Where you have it now it only tests the input when the form loads, not when it is filled and submitted
Also no need to do Array from
Lastly your test was testing the existence of ONE a-zA-Z
(() => {
'use strict'
document.querySelectorAll('.needs-validation')
.forEach(form => {
form.addEventListener('submit', event => {
const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value.trim();
const ptern = /^[A-Za-z]*$/;
isPasswordValid = ptern.test(en);
console.log( isPasswordValid)
if (!form.checkValidity() || !isPasswordValid) {
event.preventDefault()
event.stopPropagation()
console.log('not valid')
}
// else // I would expect an else here
form.classList.add('was-validated')
}, false)
})
})()
<form id="Oform" action="" class="form-control needs-validation" novalidate>
<label for=" OName">name</label>
<input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
<div class="input-group form-control">
<label class="col-sm-12" for="IPrange"> family</label>
<input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
</div>
<button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>
And if there is only one form then even less reason
(() => {
'use strict'
document.querySelector('.needs-validation')
.addEventListener('submit', event => {
const form = event.target;
form.classList.remove('was-validated')
form.classList.remove('invalid')
const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value.trim();
const ptern = /^[A-Za-z]*$/;
isPasswordValid = ptern.test(en);
if (!form.checkValidity() || !isPasswordValid) {
event.preventDefault()
event.stopPropagation()
form.classList.add('invalid')
}
else {
form.classList.add('was-validated')
}
})
})()
.invalid { border: 1px solid red; }
.was-validated { border: 1px solid green; }
<form id="Oform" action="" class="form-control needs-validation" novalidate>
<label for=" OName">name</label>
<input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
<div class="input-group form-control">
<label class="col-sm-12" for="IPrange"> family</label>
<input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
</div>
<button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>
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.
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>
Note : i searched similar questions and still couldn't fix it so i'm asking again.
i have a form and its onsubmit = "return submit()". it checks if textarea is empty. If it is then it returns false but that doesn't work.The action still goes to the next website even if text area is empty.
let firstName = document.querySelector('#firstname');
let lastName = document.querySelector('#lastname');
let password = document.querySelector('#password');
let retypePass = document.querySelector('#repassword');
let radioMale = document.querySelector('#male');
let radioFemale = document.querySelector('#female');
let textArea = document.querySelector('#textarea');
let select= document.querySelector('#select');
let button = document.querySelector('#button');
let form = document.querySelector('#form');
function submit(){
if (textArea.value = "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
HTML :`
<div class='wrapper'>
<h1>Registration Form</h1>
<form action="http://google.com" id='form' onsubmit="return submit()">
<input placeholder="First Name" type="text" id='firstname' required>
<span></span>
<br>
<input placeholder="Last Name" type="text" id='lastname' required>
<span></span>
<br>
<input placeholder="Password" type="text" id='password' required>
<span></span>
<br>
<input placeholder="Retype Password" type="text" id='repassword' required>
<span></span>
<br>
<input placeholder="Phone Number" type="tel" id='tel' >
<br>
<div class='radio'>
<h4>Selector Your Gender</h4>
<input type='radio'name='same' id='male'>Male
<input type='radio'name='same' id='female'>Female
</div>
<p style="margin:5px 0px;color:white">ADDRESS:</p>
<textarea id='textarea'></textarea>
<span></span>
<p style="margin:5px 0px;color:white">Country:</p>
<select type='country' style="width:84%" id='select'>
<option>England</option>
<option>Japan</option>
<option>America</option>
<option>France</option>
<option>NetherLands</option>
</select>
<br><br>
<input type='submit' value='submit'>
</form>
</div>
Your if systax was wrong:
if (textArea.value = "")
It should be:
if (textArea.value == "")
You must change the name of the function
Example
<form action="http://google.com" id='form' onsubmit="return validate()">
and
function validate() {
if (textArea.value == "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
try
if (!textArea.value) {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
OR
if (textArea.value == '') {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
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.