validate form with javascript with a validation expression - javascript

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>

Related

How to display all required error once with required attribute

The required attribute in input type display's once at a time. Is it possible to display required notification in html5 all at once when the user submits the form?
This snippet will help you to implement form validation.
Here we are adding a data attribute data-required to identify the required field and implement the validation logic.
var $ = jQuery;
$('#form').on('submit', function(e) {
e.preventDefault();
let validation = validateForm($(this))
})
validateForm = (formElement) => {
let form = formElement;
let valid = true;
$('.error').remove();
const generalError = "<span class='error'>This Field can not be empty</span>";
form.find('.form-group').each(function(index, item) {
let formItem = $(item).find('.form-item');
// check only inputs with validation required
if (formItem.data('required')) {
let type = formItem.data('field');
let formItemLength = formItem.val().length
if (formItem.val() === '') {
$(item).append(generalError)
valid = false
}
if (formItem.attr('type') == 'checkbox' && !formItem.is(':checked')) {
$(item).append(generalError)
valid = false
}
}
})
return valid
}
form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
form .error {
color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form id="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-item" id="name" name="name" data-field="name" data-required="required">
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input type="text" class="form-item" id="lastname" name="lastname">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" class="form-item" data-field="email" data-required="required">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" id="phone" name="phone" class="form-item" data-field="phone" data-min="6" data-max="8" data-required="required">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-item" id="password" name="password" data-field="password" data-min="6" data-max="12" data-required="required">
</div>
<div class="form-group">
<label for="agreement">Agreement</label>
<input type="checkbox" class="form-item" id="agreement" name="agreement" data-required="required">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea cols="57" id="description" name="description" rows="10" class="form-item" data-field="description"></textarea>
</div>
<div class="form-action">
<input class="form-submit" type="submit" value="Apply">
</div>
</form>

Form not going into validation function onsubmit

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>

Form validation button without submitting the form

I have a form, and I want to check validation ( if the inputs are correct) without submitting that form. How is that possible?
The validations in this example is as follows:
If the user enters and for first name and jkp for last name and clicks on the validate button, the document.write function will print success without submitting the form.
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{document.write("Correct answer");}
else{document.write("Incorrect answer");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
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 id="myform" action="#">
<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..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>
make validate but not a submit type
Changes i have made:
in js
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
in html
<input id="vali" style="background:red" type="button" value="Validate">
DEMO:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
#vali{
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
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 id="myform" action="#">
<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..">
<input type="submit" value="Submit">
<input id="vali" style="background:red" type="button" value="Validate">
</form>
You can also try AJAX requests supposing you will do the validation on the server side, also hiding the business logic from the client.
Another solution is to create a javascript method for validation that is called after focus lost/key up which takes the elements by their id and passes them to this function.
You can simply add event.preventDefault() to the submit event if the validation fails:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp") {
alert("Success");
}
else {
event.preventDefault();
alert("failed");
}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
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 id="myform" action="#">
<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..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>
Not checked but you can use onchange(),
The change event occurs when the value of an element has been changed (only works on input, textarea and select elements).
The change() method triggers the change event or attaches a function to run when a change event occurs.
$( "#myform" ).change(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp"){
alert("Your answers are correct!");
}
else{
alert("Your answer is not correct");
}
}

How to validate a multiple step form and message display for each and every fields

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

Login validation function

I have been trying to get this to work for a while now. I cannot connect the login function to the form.
I have tried onsubmit on both the form tag and the button input tag, i have tried onclick but it does not get the code from js function.
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!--<link rel="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="util.js"></script>
<script src="JavaScript.js"></script>
<script type="text/javascript"></script>
<style>
#container {
width: 1200px;
}
#map {
width: 80%;
min-height: 600px;
/*float: right;*/
margin-top: 15px;
margin-left: auto;
margin-right: auto;
}
#img {
width: 150px;
height: 150px;
float: left;
margin-top: auto;
}
/*sökruta*/
#searchBox {
background-color: #ffffff;
padding: 5px;
font-family: 'Roboto','sans-serif';
margin-bottom: 10px;
float: top;
}
/*
html, body {
height: 100%;
margin: 0;
padding: 0;
}
*/
.search-form .form-group {
float: right !important;
transition: all 0.35s, border-radius 0s;
width: 32px;
height: 32px;
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
border-radius: 25px;
border: 1px solid #ccc;
}
.search-form .form-group input.form-control {
padding-right: 20px;
border: 0 none;
background: transparent;
box-shadow: none;
display:block;
}
.search-form .form-group input.form-control::-webkit-input-placeholder {
display: none;
}
.search-form .form-group input.form-control:-moz-placeholder {
/* Firefox 18- */
display: none;
}
.search-form .form-group input.form-control::-moz-placeholder {
/* Firefox 19+ */
display: none;
}
.search-form .form-group input.form-control:-ms-input-placeholder {
display: none;
}
.search-form .form-group:hover,
.search-form .form-group.hover {
width: 100%;
border-radius: 4px 25px 25px 4px;
}
.search-form .form-group span.form-control-feedback {
position: absolute;
top: -1px;
right: -2px;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
color: #3596e0;
left: initial;
font-size: 14px;
}
.form-group {
max-width: 300px;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body id="container">
<img id="img" src="http://www2.math.su.se/icsim/images/sterik.jpg" alt="Stockholm"/>
<div class="row">
<br>
<div class="col-md-4 col-md-offset-3">
<form action="" class="search-form">
<div class="form-group has-feedback">
<label id="Search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="searchField" placeholder="Sök">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in" onclick="login()">
</form>
</div>
<div id="map">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPkC40KP9lMKHUsJW7q403qnwRqYkTno&callback=initMap">
</script>
</div>
</body>
JavaScript.js
function login() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
}
I have created working JSFiddle - Please Check : https://jsfiddle.net/5w6fg52m/1/
Below Code working fine :
<script>
//just change function name as it's conflict with button id
function login1() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
return false;
}
</script>
//HTML
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="button" id="login" value="Logga in" onclick="return login1();">
</form>
</div>
-> I have created other version of JSFiddle, so you come to know conflict issue easily: https://jsfiddle.net/5w6fg52m/2/
Here i have keep function name same(login) and change ID of submit button.
You can set the submit event directly to your like
document.getElementById("loginForm").onsubmit = function() { ... };
Bellow a sample snippet :
window.onload = function(){
document.getElementById("loginForm").onsubmit = function() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if (username === "admin" &&
password === "123") {
alert("validation succeeded");
//location.href = "adminView.php";
} else {
alert("validation failed");
//location.href = "index1.html";
}
// to prevent submit
return false;
}
}
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in">
</form>
</div>
This happens when you declare variable or function with the same name as declare before. just rename login function or rename id="login".

Categories