This is a signup form, after inputting all the values, the validation()must validate the inputs and if all inputs are valid, should be redirected to home page, but my form is not entering the Javascript validation on submitting the form.
This is my code:
<!DOCTYPE html>
<html><head>
<style>
body {font-family: Arial, Helvetica, sans-serif;
background-color: black;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #C0C0C0;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ffbf00;
outline: none;
}
hr {
border: 1px solid #000000;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: darkgreen;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 50%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Add padding to container elements */
.container {
padding: 16px;
background-color: white;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
.signupbtn {
width: 50%;
}
</style>
<script type="text/javascript">
function validation() {
alert('in..');
var uname = document.signup_form.username.value;
var mail= document.signup_form.email.value;
var num= document.signup_form.phone.value;
var pass= document.signup_form.psw.value;
var des= document.signup_form.desg.value;
alert('validating...');
if allLetter(uname){
if ValidateEmail(mail){
if check_phonenumber(num){
if CheckPassword(pass){
if desgselect(des){
}
}
}
}
}
return false;
}
function allLetter(uname)
{
alert('validating username');
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
alert('corret name');
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(signup_form.email.value))
{
alert('valid mail ID');
return (true)
}
alert("You have entered an invalid email address!");
return (false)
}
function check_phonenumber(num)
{
var phoneno = /^\d{10}$/;
if((num.value.match(phoneno))
{
alert('valid phone number');
return true;
}
else
{
alert("invalid phone number");
return false;
}
}
function CheckPassword(pass)
{
var passw= /^[A-Za-z]\w{7,15}$/;
if(pass.value.match(passw))
{
alert('Correct, try another...');
return true;
}
else
{
alert('Wrong...!');
return false;
}
}
function desgselect(des)
{
if(des.value == "Default")
{
alert('Select your designation from the list');
desg.focus();
return false;
}
else
{
alert('selected correct designation');
return true;
}
}
//}
</script>
</head>
<body>
<form name="signup_form" onsubmit="return validation()" action="main.html" method="post" style="border:1px solid #ccc">
<div class="container">
<h1><center>Sign Up</center></h1>
<p><center>Please fill in this form to create an account.</center></p>
<hr>
<label for="username"><b>Name</b></label>
<input type="text" placeholder="Enter your full name" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="phone"><b>Phone</b></label>
<input type="text" id="phone" name="phone" placeholder="Enter your mobile number" required><br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="desg"><b>Designation</b></label>
<select name="desg">
<option selected="" value="Default">(Please select your designation)</option>
<option value="am">Asst. Manager</option>
<option value="dm">Department Manager</option>
<option value="mm"> Mart Manager</option>
<option value="sp">Sales Person</option>
</select><br>
<br><label><b>Gender</b>
<input type="radio" name="gender" value="male" > Male
<input type="radio" name="gender" value="female"> Female<br>
</label>
<p><center>By creating an account you agree to our Terms & Privacy.</center></p>
<div class="clearfix" align="center">
<button type="submit" class="signupbtn" onclick="validation(this.signup_form);"><b>Join Us</b></button>
</div>
</div>
</form>
</body>
</html>
I tried every possible way, but I am not able to resolve the problem.
When you have button type ="submit" in form, your click on submit button will refresh the page.
hence even if your validation function is executed you can not see error or success message.
what you need to do is prevent this default behaviour either with event.preventDefault() in validation method or change type of button to button.
In your case change button type="submit" to type="button".
You had many syntax errors in your code, which caused it to not execute.
You should also use addEventListener instead of an inline onsubmit event handler.
<!DOCTYPE html>
<html><head>
<style>
body {font-family: Arial, Helvetica, sans-serif;
background-color: black;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #C0C0C0;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ffbf00;
outline: none;
}
hr {
border: 1px solid #000000;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: darkgreen;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 50%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Add padding to container elements */
.container {
padding: 16px;
background-color: white;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
.signupbtn {
width: 50%;
}
</style>
<script type="text/javascript">
function validation() {
alert('in..');
var uname = document.signup_form.username.value;
var mail= document.signup_form.email.value;
var num= document.signup_form.phone.value;
var pass= document.signup_form.psw.value;
var des= document.signup_form.desg.value;
alert('validating...');
if (allLetter(uname)&&ValidateEmail(mail)&&check_phonenumber(num)&&CheckPassword(pass)&&desgselect(des)){
return true;
}
return false;
}
function allLetter(uname){
alert('validating username');
var letters = /^[A-Za-z]+$/;
if(uname.match(letters)) {
alert('corret name');
return true;
}else{
alert('Username must have alphabet characters only');
return false;
}
}
function ValidateEmail(mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(signup_form.email.value)){
alert('valid mail ID');
return (true);
}
alert("You have entered an invalid email address!");
return (false);
}
function check_phonenumber(num){
var phoneno = /^\d{10}$/;
if(num.match(phoneno)){
alert('valid phone number');
return true;
} else{
alert("invalid phone number");
return false;
}
}
function CheckPassword(pass){
var passw= /^[A-Za-z]\w{7,15}$/;
if(pass.match(passw)) {
alert('Correct, try another...');
return true;
}else{
alert('Wrong...!');
return false;
}
}
function desgselect(des){
if(des == "Default"){
alert('Select your designation from the list');
desg.focus();
return false;
}else{
alert('selected correct designation');
return true;
}
}
//}
window.onload = function(){
document.getElementById("signupform").addEventListener("submit", function(e){
validation();
});
}
</script>
</head>
<body>
<form id="signupform" name="signup_form" action="main.html" method="post" style="border:1px solid #ccc">
<div class="container">
<h1><center>Sign Up</center></h1>
<p><center>Please fill in this form to create an account.</center></p>
<hr>
<label for="username"><b>Name</b></label>
<input type="text" placeholder="Enter your full name" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="phone"><b>Phone</b></label>
<input type="text" id="phone" name="phone" placeholder="Enter your mobile number" required><br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="desg"><b>Designation</b></label>
<select name="desg">
<option selected="" value="Default">(Please select your designation)</option>
<option value="am">Asst. Manager</option>
<option value="dm">Department Manager</option>
<option value="mm"> Mart Manager</option>
<option value="sp">Sales Person</option>
</select><br>
<br><label><b>Gender</b>
<input type="radio" name="gender" value="male" > Male
<input type="radio" name="gender" value="female"> Female<br>
</label>
<p><center>By creating an account you agree to our Terms & Privacy.</center></p>
<div class="clearfix" align="center">
<button type="submit" class="signupbtn" onclick="validation(this.signup_form);"><b>Join Us</b></button>
</div>
</div>
</form>
</body>
</html>
Related
<html>
<script>
function passwordvalidation() #validate if password is strong and if botth passwords are equal
{
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
alert(x);
if (x == ""||y==""||z=="") {
alert("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
</script>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<form name="signup" action="/login" onsubmit="return passwordvalidation()" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
You have several errors in these lines:
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
You can use many methods to retrieve the inputs values, but this way is throwing errors. Check how to do it by using document.getElementBy*** or similar
It is calling the validation function, but you made a spelling mistake in second and third line. Correct
document.form --> document.forms document.form is undefined and your function is exiting with TypeError when you call document.form["signup"] without returning false, and thus your form is navigating to defined action
function passwordvalidation(form)
{
var x=form["psw"].value;
var y=form["psw-repeat"].value;
var z=form["email"].value;
if (x == ""||y==""||z=="") {
alert("form must be filled out");
console.log("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
<form name="signup" action="/login" onsubmit="return passwordvalidation(this)" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit"class="signupbtn">Sign Up</button>
</div>
</div>
</form>
I'm trying to create checks to validate the input of a user, such as whether he filled it out and is it the correct input. I want it to highlight the fields that contain an error.
I already asked and I was told to create a class however I don't know how to do that.
There is also
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//passwords is too short
if (!form['password'].value.length < 4) {
error.push("Password is too short (Minimum 4 characters)");
}
//height is not a number
if (isNaN(Number(form['height'].value))) {
error.push("Height is not a number");
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
The CSS (form.css):
body {
font-family: sans-serif;
font-size: .9em;
}
form {
width: 26em;
}
label {
font-weight: bold;
float: left;
}
input.wide {
padding: .125em;
width: 25.125em;
}
input.medium {
padding: .125em;
width: 12em;
}
input.narrow {
padding: .125em;
width: 8em;
}
#othercolour {
visibility: hidden;
}
The style.css
body {
font-family: sans-serif;
font-size: .9em;
background-color: rgb(166, 183, 183);
color: black;
}
div#body {
width: 30em;
margin: auto;
padding: 1em 2em;
background-image: url(background.png);
background-repeat: repeat-x;
background-color: rgb(224, 230, 230);
}
h1,h2 {
color: rgb(47, 79, 79);
}
h2 {
margin: .25em 0em .25em 0em;
}
a {
text-decoration: none;
color: rgb(132, 156, 156);
color: white;
font-weight: bold;
}
a:hover {
color: yellow;
}
td, th {
vertical-align: top;
text-align: left;
}
img {
border: 0px;
}
p, .clear {
qclear: both;
}
#catalog {
float: left;
width: 50%;
}
#content {
float: right;
width: 46%;
}
#cart {
border: 1px solid #cccccc;
padding: 0em .5em;
}
#cart form {
display: inline;
}
#cart input.text {
width: 2em;
text-align: right;
}
#welcome {
}
#navigation {
}
#navigation span {
color: rgb(131, 155, 155);
}
#navigation ul {
list-style: none;
padding: 0;
margin: 0;
}
#navigation li {
float: left;
background-color: pink;
border-bottom: solid 1px;
}
#navigation li a {
display: block;
width: 8em;
text-decoration: none;
font-weight: bold;
text-align: center;
padding: .25em;
background-color: rgb(97, 124, 124);
}
#navigation li a:hover {
background-color: rgb(47, 79, 79);
}
You can set the input's CSS border-color property to highlight the field.
var input = document.querySelector('input'),
form = document.querySelector('form');
form.addEventListener('submit', function(e){
e.preventDefault();
if(!input.value.trim()){//if value of input is empty
input.style.borderColor = "red";
} else {
input.style.borderColor = "green";
}
});
<form>
<input placeholder="Enter something">
<br/>
<button>Validate</button>
</form>
If you use the HTML5 validation attributes, then all you’ll need is to set up a CSS rule using the :invalid pseudo class:
:invalid { . . . }
To add a class, use JavaScript's classList.add() function.
Example
function check() {
var element = document.getElementById("input");
if (element.value != "") {
document.write("Valid!");
} else {
element.classList.add("invalid");
}
}
.invalid {
background-color: rgba(255,0,0,.7);
color: white;
}
.invalid::placeholder {
color: white;
}
<input type="text" placeholder="Type Something..." id="input">
<button onclick="check();">Check</button>
How to Validate? Don’t allow Gmail, Yahoo, etc email addresses. And one more issue is that when all the fields are not entered submit should be disabled. when i fill all submit is enabled and when i remove one input after filling it, submit should be disabled, but still it's enabled. How to fix that?
$("#passwordv").on("focusout", function (e) {
if ($(this).val() != $("#passwordvConfirm").val()) {
$("#passwordvConfirm").removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$("#passwordvConfirm").removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$("#passwordvConfirm").on("keyup", function (e) {
if ($("#passwordv").val() != $(this).val()) {
$(this).removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$(this).removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$(document).ready(function () {
$('#passwordv').keyup(function () {
$('#result').html(checkStrength($('#passwordv').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
$('.form').find('input, textarea').on('keyup blur focus', function (e) {
var $this = $(this),
label = $this.prev('label');
if (e.type === 'keyup') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.addClass('active highlight');
}
} else if (e.type === 'blur') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.removeClass('highlight');
}
} else if (e.type === 'focus') {
if ($this.val() === '') {
label.removeClass('highlight');
} else if ($this.val() !== '') {
label.addClass('highlight');
}
}
});
$('.tab a').on('click', function (e) {
e.preventDefault();
$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');
target = $(this).attr('href');
$('.tab-content > div').not(target).hide();
$(target).fadeIn(600);
});
*,
*:before,
*:after {
box-sizing: border-box;
}
html {
overflow-y: scroll;
}
body {
background: #f1f0ee;
font-family: 'Titillium Web', sans-serif;
}
a {
text-decoration: none;
color: #1ab188;
transition: .5s ease;
}
a:hover {
color: #179b77;
}
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 130px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
#media only screen and (max-width: 768px) {
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 30px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
}
.tab-group {
list-style: none;
padding: 0;
margin: 0 0 40px 0;
}
.tab-group:after {
content: "";
display: table;
clear: both;
}
.tab-group li a {
display: block;
text-decoration: none;
padding: 15px;
background: rgba(160, 179, 176, 0.25);
color: #a0b3b0;
font-size: 20px;
float: left;
width: 50%;
text-align: center;
cursor: pointer;
transition: .5s ease;
}
.tab-group li a:hover {
background: #179b77;
color: #ffffff;
}
.tab-group .active a {
background: #1ab188;
color: #ffffff;
}
.tab-content>div:last-child {
display: none;
}
h1 {
text-align: center;
color: #ffffff !important;
font-weight: 300;
margin: 0 0 40px !important;
}
label {
position: absolute;
-webkit-transform: translateY(6px);
transform: translateY(6px);
left: 13px;
color: rgba(255, 255, 255, 0.5);
transition: all 0.25s ease;
-webkit-backface-visibility: hidden;
pointer-events: none;
margin-top: 18px;
}
label .req {
margin: 2px;
color: #1ab188;
}
label.active {
-webkit-transform: translateY(-25px);
transform: translateY(-25px);
left: 2px;
font-size: 14px;
}
label.active .req {
opacity: 0;
}
label.highlight {
color: #ffffff;
}
input,
textarea {
font-size: 22px;
display: block;
width: 100%;
height: 100%;
padding: 8px 10px;
background: none;
background-image: none;
border: 1px solid #a0b3b0;
color: #ffffff;
border-radius: 0;
transition: border-color .25s ease, box-shadow .25s ease;
}
input:focus,
textarea:focus {
outline: 0;
border-color: #1ab188;
}
textarea {
border: 2px solid #a0b3b0;
resize: vertical;
}
.field-wrap {
position: relative;
margin-bottom: 25px;
}
.top-row:after {
content: "";
display: table;
clear: both;
}
.top-row>div {
float: left;
width: 48%;
margin-right: 4%;
}
.top-row>div:last-child {
margin: 0;
}
.button {
border: 0;
outline: none;
border-radius: 50px;
padding: 15px 0;
font-size: 20px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .1em;
background: #1ab188;
color: #ffffff;
transition: all 0.5s ease;
-webkit-appearance: none;
}
.button:hover,
.button:focus {
background: #179b77;
}
.button-block {
display: block;
width: 50%;
margin: 0 auto;
}
.forgot {
text-align: right;
}
#toast-container {
top: 4% !important;
right: 40% !important;
left: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="form">
<ul class="tab-group">
<li class="tab active">Log In</li>
<li class="tab">Sign Up</li>
</ul>
<div class="tab-content">
<div id="login">
<form id="form_id" method="post" name="myform">
<div class="field-wrap">
<label>
User Name<span class="req">*</span>
</label>
<input type="text" autocomplete="off" name="username" id="username" required>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" autocomplete="off" name="password" id="password" required>
</div>
<p class="forgot">Forgot Password?</p>
<input type="button" value="Log in" id="submit" onclick="validate()" class="button button-block">
</form>
</div>
<div id="signup">
<form>
<div class="field-wrap">
<label>
Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordv" type="password" class="validate" required autocomplete="off" />
<span id="result" style="color: white;"></span>
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" />
</div>
<label class="field-wrap" id="btn-1" style="display: none;color: white;font-size: 15px">password
didn't match
</label>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed"
disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Okay, so I broke down your code a bit to make it more easily understood. This example will only include your signup part of your application.
As I explained in my comment, what you could do to test the E-mails to see whether they are a Gmail or a Yahoo E-mail, is by using regular expressions (RegExp).
Example of Gmail RegExp:
/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g
Example of Yahoo RegExp:
/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i
In my example, I'll put them into functions for simplicity.
Gmail RegExp function:
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
Yahoo RegExp function:
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
Now, I altered some of your code a bit in order to have some selectors to go by. Some of your input fields did not contain any selectors, such as name or id, while others did. So I took the liberty to add some.
One thing to note, is that the id you assigned your password input field (not the password confirm one, but the one before that) had some id conflicts. Therefore I took the liberty to change the id accordingly.
I then made a function handling all the validation logic of the input fields to fit your needs in your question. However, again, pretty simplified. I would suggest you alter it to fit your solution a little bit better, but it should give you more than a general idea.
Full Example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
function validateInputs() {
reGmail=regExpGmail();
reYahoo=regExpYahoo();
var result = true;
var nameCheck=$('#nameField').val();
var emailCheck=$('#emailField').val();
var compDetailsCheck=$('#compDetailsField').val();
var passwordCheck=$('#passwordvz').val();
var passwordConfirmCheck=$('#passwordvConfirm').val();
if(!nameCheck) {
result=false;
$('#nameError').html('Name is missing!');
}
else {
$('#nameError').html('');
}
if(!emailCheck) {
result=false;
$('#emailError').html('E-mail is missing!');
}
else if(reGmail.test(emailCheck)) {
result=false;
$('#emailError').html('Gmail is not allowed!');
}
else if(reYahoo.test(emailCheck)) {
result=false;
$('#emailError').html('Yahoo is not allowed!');
}
else {
$('#emailError').html('');
}
if(!compDetailsCheck) {
result=false;
$('#compDetailsError').html('Company Details is missing!');
}
else {
$('#compDetailsError').html('');
}
if(!passwordCheck) {
result=false;
$('#passwordError').html('Password is missing!');
}
else {
$('#passwordError').html('');
}
if(passwordCheck != passwordConfirmCheck) {
result=false;
$('#passwordError2').html('The passwords do not match!');
}
else {
$('#passwordError2').html('');
}
if(result == true) {
$('#btn').removeAttr('disabled');
$('#btn').css("cursor", "");
alert('Everything ok, you may now press the submit button!');
}
}
</script>
<div class="form">
<div class="tab-content">
<div id="signup">
<form>
<div class="field-wrap">
<span id="nameError" style="color: red !important;"></span><br />
<label>
Name<span class="req">*</span>
</label>
<input type="text" id="nameField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="emailError" style="color: red !important;"></span><br />
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="emailField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="compDetailsError" style="color: red !important;"></span><br />
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" id="compDetailsField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="passwordError" style="color: red !important;"></span><br />
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordvz" type="password" class="validate" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<span id="passwordError2" style="color: red !important;"></span><br />
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed" disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Screenshots of the validation process:
So I have a form and I am trying to validate it to make sure no other characters are submitted I know theirs a validation expression but I do not know how to apply it.I just want it where if the user puts any invalid character that may interfere then it just return false. I tried but it does not seem to work, also please help me make my code more efficient if there is any way thank you
function validateForm() {
var name = document.forms["theForm"]["fname"].value;
var lastName = document.forms["theForm"]["lname"].value;
var email = document.forms["theForm"]["femail"].value;
var subject = document.forms["theForm"]["subject"].value;
if (name == "") {
window.alert("Missing First Name.");
name.focus();
return false;
}
if (lastName == "") {
alert("Missing Last Name");
return false;
}
if (email == "") {
alert("Missing Email");
return false;
}
if (subject == "") {
alert("Incomplete Action");
return false;
}
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #993b3b;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #B0B0B0;
}
.formCont {
text-align: left;
margin: 152.5px 0;
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
<div class="formCont">
<form name="theForm" onsubmit="return validateForm()" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="femail">Email</label>
<input type="text" id="femail" name="Email" placeholder="Your email.."
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
Ok, so since this is a college project. I'm assuming you have to write vanilla JS (if not jQuery is a super better alternative).
A couple of things to start off:
name === ""
Is better than name == "" Because of JavaScript's type coercion.
Also, HTML now has an email input type. So
<input type="email" id="femail" name="Email" placeholder="Your email..">
Why do you have window.alert in one place and alert in other places. Oh goodness. This is becoming a code review :).
Anyway, like I said before, if jQuery is a choice, please, please do.
#peterb mentioned correctly here is an example of using jquery
function validateForm() {
var name = $("#fname").val();
var lastName = $("#lname").val();
var email = $("#femail").val();
var subject =$("#subject").val();
if (name == "" || name ==null || name==undefined) {
alert("Missing First Name.");
markerror("#fname")
return false;
}
if (lastName == "" || lastName ==null || lastName==undefined) {
alert("Missing Last Name");
markerror("#lname")
return false;
}
if (email == "" || email ==null || email==undefined) {
alert("Missing Email");
markerror("#femail")
return false;
}
if (subject == "" || subject ==null || subject==undefined) {
alert("Incomplete Action");
markerror("#subject")
return false;
}
}
function markerror(index){
$(index).css("border", "1px solid red");
$(index).focus();
setTimeout(function () {
$(index).css("border", "1px solid #ccc");
}, 4000);
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #993b3b;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #B0B0B0;
}
.formCont {
text-align: left;
margin: 152.5px 0;
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="theForm" onsubmit="return validateForm()" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="femail">Email</label>
<input type="text" id="femail" name="Email" placeholder="Your email.."
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
How to validate a multiple step form and message display for each and every fields example:please enter your email and I also want all the error message to
be display at the same time :suppose I click on next button I should display all How to validate a multiple step form and message display for each and every feilds How to validate a multiple step form and message display for each and every fields
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use Jquery.validate.min.js file which contains validate method.
Refer the following code below:
function valid(){
$("#rform").validate({
rules:{
uname:"required", // uname, email are input names
umail:{
required:true,
email:true
},
upass:{
required:true,
minlength:8
}
},
messages:{
uname:"Please enter full name",
umail:{
required:"Please enter email id",
email:"Please enter valid email id"
},
upass:
{
required:"please provide password",
minlength:"min length of password is 8"
}
},
submitHandler :function(form){
// alert("it works!");
console.log("it works!");
// form.submit();
funreg(); //function to be called after submit button is pressed and al inputl fields are valids
}
});
}