It is about validation of form - javascript

**Below is the code for basic user registration form but it is not validating the form... Please can anyone tell me where is the problem. Except validation remaining code is working. Please tell me what to do for it*
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^[a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<html>
<head>
</head>
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return
validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>
</html>

Here you made several mistake in your code.
Make sure onsubmit="return validateForm()" have no any blank space before return
There is a error in your regular expression
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/; You made mistake in this. you forget to add ( at the starting of expression after /^
Below is the working snippet with validation.
Check it hope it will helps you
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>

Related

eventListener works on click 1. But fails on click 2

So i am making a signup form with action="signup.inc.php" But im handling the validation in javascript.
If the fields are empty or the password don't match the input gets a red border and the placeholder is replaced.
This works perfectly on the first click. But as soon as i click again he just shoots to signup.inc.php.
I need those validations to be done before we go to the signup.inc.php file.
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
let result = false;
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
inputArr.forEach(function (input){
if (input.value.trim() === ''){
showError(input, 'this field is required');
} else {
showSucces(input);
result = true;
}
});
}
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
} else {
result = true;
}
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e){
if (result !== true) {
requiredFields ([firstname, lastname, email, username, password, passwordRepeat]);
matchPasswords (password, passwordRepeat);
e.preventDefault();
} else {
result = true;
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
Your problem is that if any of the inputs are valid, result is set to true and so on the next submit the inputs are not checked and the form submits. You can work around that by always testing all the inputs, returning the error status from each input checking function and checking that they all return true:
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
result = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, 'this field is required');
result = false;
} else {
showSucces(input);
}
});
return result;
}
function matchPasswords(input1, input2) {
result = true;
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
result = false;
}
return result;
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e) {
let result = true;
result = result && requiredFields([firstname, lastname, email, username, password, passwordRepeat]);
result = result && matchPasswords(password, passwordRepeat);
if (!result) {
e.preventDefault();
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
change all validation functions like
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
return false;
}
return true;
}
signupForm.addEventListener('submit', function(e){
if(!requiredFields ([firstname, lastname, email, username, password, passwordRepeat]) &&
!matchPasswords (password, passwordRepeat)){
e.preventDefault();
}
});

Checkbox validation in form

I have a code like this and cannot validate the checkbox field while it is checked. Can you help me please? I mean only the #check id in checkbox input field. Something doesn't work me.
Email works correctly, name also, but the checkbox I don't know how to validate it to have it checked by user. If not it should give us information "Accept policy".
$(function() {
var form = document.querySelector("#form");
form.addEventListener("submit", function(e) {
e.preventDefault();
var valid;
valid = validateContact();
if (valid) {
jQuery.ajax({
url: "contact-form.php",
data: '&name=' + $("#name").val() +
'&email=' + $("#email").val() +
'&address=' + $("#address").val() +
'&check=' + $("#check").val() +
'&message=' + $("#message").val(),
type: "POST",
success: function() {
document.getElementById("form").reset();
$('#contact-after-msg').text('Dziękujemy za złożenie zamówienia. Odezwiemy się do Państwa jeszcze dziś.');
},
error: function() {
alert('Coś poszło nie tak, spróbuj ponownie');
}
});
}
function validateContact() {
var valid = true;
if (!$("#name").val()) {
$("#name").css("border", "solid 1px #ff5d5d");
$("#name-info").html("Podaj imię i nazwisko");
valid = false;
} else {
$("#name").css("border", "none");
$("#name-info").html("");
}
if (!$("#address").val()) {
$("#address").css("border", "solid 1px #ff5d5d");
$("#address-info").html("Podaj adres wysyłki");
valid = false;
} else {
$("#address").css("border", "none");
$("#address-info").html("");
}
if (!$("#email").val()) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Podaj adres e-mail");
valid = false;
} else if (!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Adres e-mail jest niepoprawny");
valid = false;
} else {
$("#email").css("border", "none");
$("#email-info").html("");
}
if (!$("#check").val().checked === true) {
$("#check").css("border", "solid 1px #ff5d5d");
$("#check-info").html("Accept Policy");
valid = false;
} else {
$("#check").css("border", "none");
$("#check-info").html("");
}
return valid;
}
});
});
<form class="t-contact-form__form" id="form" novalidate>
<div class="t-contact-form__item">
<span id="name-info"></span>
<input class="t-contact-form__field" name="name" placeholder="Imię i nazwisko" type="text" id="name" required>
</div>
<div class="t-contact-form__item">
<span id="email-info"></span>
<input class="t-contact-form__field" name="email" placeholder="Adres email" type="email" id="email" required>
</div>
<div class="t-contact-form__item">
<span id="address-info"></span>
<input class="t-contact-form__field" name="address" placeholder="Adres" type="text" id="address" required>
</div>
<div class="t-contact-form__item">
<textarea class="t-contact-form__field" name="message" placeholder="Masz dodatkowe życzenia? Zamawiasz więcej egzemplarzy?" required id="message"></textarea>
<div class="t-contact-form__item">
<span id="check-info"></span>
<h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check" required>I accept the terms.
</h5>
</div>
<div class="t-contact-form__button">
<button class="c-btn c-button c-button--contact-send" name="submit" type="submit" id="contact-submit">Buy</button>
<div class="t-contact-form__policy-buttons">
<a class="c-btn" href="images/REGULAMIN ZAMÓWIENI.pdf">Policy
<a class="c-btn" href="images/POLITYKA PRYWATNOŚCI.pdf">Terms
</div>
</div>
<div class="contact-msg-success" id="contact-after-msg"></div>
</div>
</form>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<form class="t-contact-form__form" id="form" novalidate>
<div class="t-contact-form__item">
<span id="name-info"></span>
<input class="t-contact-form__field" name="name" placeholder="Imię i nazwisko" type="text" id="name" required>
</div>
<div class="t-contact-form__item">
<span id="email-info"></span>
<input class="t-contact-form__field" name="email" placeholder="Adres email" type="email" id="email" required>
</div>
<div class="t-contact-form__item">
<span id="address-info"></span>
<input class="t-contact-form__field" name="address" placeholder="Adres" type="text" id="address" required>
</div>
<div class="t-contact-form__item">
<textarea class="t-contact-form__field" name="message" placeholder="Masz dodatkowe życzenia? Zamawiasz więcej egzemplarzy?" required id="message"></textarea>
<div class="t-contact-form__item">
<span id="check-info"></span>
<h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check" required>I accept the terms.
</h5>
</div>
<div class="t-contact-form__button">
<button class="c-btn c-button c-button--contact-send" name="submit" type="submit" id="contact-submit">Buy</button>
<div class="t-contact-form__policy-buttons">
<a class="c-btn" href="images/REGULAMIN ZAMÓWIENI.pdf">Policy
<a class="c-btn" href="images/POLITYKA PRYWATNOŚCI.pdf">Terms
</div>
</div>
<div class="contact-msg-success" id="contact-after-msg"></div>
</div>
</form>
<script>
$(function() {
var form = document.querySelector("#form");
form.addEventListener("submit", function(e) {
e.preventDefault();
var valid;
valid = validateContact();
if (valid) {
jQuery.ajax({
url: "contact-form.php",
data: '&name=' + $("#name").val() +
'&email=' + $("#email").val() +
'&address=' + $("#address").val() +
'&check=' + $("#check").val() +
'&message=' + $("#message").val(),
type: "POST",
success: function() {
document.getElementById("form").reset();
$('#contact-after-msg').text('Dziękujemy za złożenie zamówienia. Odezwiemy się do Państwa jeszcze dziś.');
},
error: function() {
alert('Coś poszło nie tak, spróbuj ponownie');
}
});
}
function validateContact() {
var valid = true;
if (!$("#name").val()) {
$("#name").css("border", "solid 1px #ff5d5d");
$("#name-info").html("Podaj imię i nazwisko");
valid = false;
} else {
$("#name").css("border", "none");
$("#name-info").html("");
}
if (!$("#address").val()) {
$("#address").css("border", "solid 1px #ff5d5d");
$("#address-info").html("Podaj adres wysyłki");
valid = false;
} else {
$("#address").css("border", "none");
$("#address-info").html("");
}
if (!$("#email").val()) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Podaj adres e-mail");
valid = false;
} else if (!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Adres e-mail jest niepoprawny");
valid = false;
} else {
$("#email").css("border", "none");
$("#email-info").html("");
}
if (!$('#check').is(':checked')) {
$("#check").css("border", "solid 1px #ff5d5d");
$("#check-info").html("Accept Policy");
valid = false;
} else {
$("#check").css("border", "none");
$("#check-info").html("");
}
return valid;
}
});
});
</script>
if (!$('#check').is(':checked')) { This line validate checkbox selected or not. Hope it helps.

Validate login form through JavaScript (Suggestion)

I have used pure JavaScript to validate this login form consider the below example and also check out the live demo here https://codepen.io/uicreation/pen/xpdbKe
hope it will be help you to understand how JavaScript validation is works.
Live Demo
if(document.getElementsByClassName('firstForm')[0]){
document.getElementsByClassName('firstForm')[0].onsubmit = function(e){
e.preventDefault();
var field = this;
var email = field.querySelector('input[type=email]');
var pass = field.querySelector('input[type=password]');
var regex = /^(([^<>()[\]\\.,;:\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(!regex.test(email.value)){
console.log("enter a valid email address")
} else if(pass.value.length < 8){
console.log("password should be greater than 8 characters")
} else {
console.log("success!")
}
}
}
form {
margin: 30px 0 0 30px;
}
fieldset {
padding:5px;
}
label {
min-width:60px;
display: inline-block;
}
input[type=submit]{
margin-top:5px;
margin-left:5px;
}
<form class="firstForm" novalidate>
<fieldset>
<label>Email</label>
<input type="email" name="email" placeholder="Enter Email" />
</fieldset>
<fieldset>
<label>Password</label>
<input type="password" name="password" placeholder="Enter Password" />
</fieldset>
<input type="submit" value="Login" />
</form>

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

My register form keeps refreshing the page

on my local server it works just fine but as soon as I take it live it starts only refershing the page instead of calling the validation.
This is my jquery:
<script>
$("form#registerform").submit(
function (e) {
e.preventDefault();
function validateForm() {
var RegisterUsername = document.forms["contactForm"]["RegisterUsername"].value;
var FirstName = document.forms["contactForm"]["FirstName"].value;
var LastName = document.forms["contactForm"]["LastName"].value;
var Email = document.forms["contactForm"]["Email"].value;
var RegisterPassword = document.forms["contactForm"]["RegisterPassword"].value;
if (RegisterUsername == null || RegisterUsername == "") {
$(".error-messages").text("Username required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (FirstName == null || FirstName == "") {
$(".error-messages").text("First name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
} else if (LastName == null || LastName == "") {
$(".error-messages").text("Last name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (Email == null || Email == "") {
$(".error-messages").text("Email required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (RegisterPassword == null || RegisterPassword == "") {
$(".error-messages").text("Password required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
}
}
</script>
This is my html:
<form id="registerform" name="contactForm" action="" onsubmit="return validateForm()" method="post">
<div class="pl-land-input">
<input class="email text-input" id="RegisterUsername" pattern=".{3,}" title="3 characters minimum" name="RegisterUsername" placeholder="Username" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" type="email" placeholder="Email" name="Email" id="Email">
</div>
<div class="pl-land-input">
<input class="email text-input" id="RegisterPassword" name="RegisterPassword" placeholder="Password" type="password">
</div>
<button type="submit" value="Submit" class="signup-plland">Sign up</button>
</form>
I have been trying to get my head around it and kept customizing it but I couldn't figure out the problem there was no problem in console for calling the Jquery libs.
I hope I can solve this asap.

Categories

Resources