Linking two pages - javascript

I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;

Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}

Related

new input replace Instead of append

Here is the html that I wrote for program
It's working but append is not working.
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6 justify-content-center">
<span>Full Name :</span>
<input id="name" type="name" class="d-flex mb-3">
<span>Email :</span>
<input id="email" type="email" name="email" class="d-flex mb-3">
<span>Comment :</span>
<input id="comment" type="text" class="d-flex mb-3">
<button id="btn" class="mt-3">Submit</button>
</div>
<div class="col-md-6">
<p id="demo"></p>
</div>
</div>
</div>
name and comment are inputs.
I type some text but append doesn't working and the new text that entered replace the first one.
function SubmitComment(name, comment) {
let newComment = censor(comment)
for (let i = 0; i < name.length; i++) {
let demo = $("#demo");
demo.html("")
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "swan") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Am not sure why your looping the name property, but here is a working example!
function Submit() {
SubmitComment($('.name'), $('.comment'));
}
function SubmitComment(name, comment) {
let newComment = censor(comment)
let demo = $("#demo");
demo.html("")
for (let i = 0; i < name.length; i++) {
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "kilt") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="name" />
<input class="comment" />
<button onClick="Submit()">Submit</button>
<div id="demo"></div>

Regular Expression always false

So I am writing some javascript to check if a user inputs a gmail address.
At the moment I have the code thats below, but no matter what I do it is giving me false. even when the input has #gmail.com...I feel that the mistake is how I am grabbing the user input in a variable and then testing it with test().
Javascript:
<script>
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {
}
}
</script>
html
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input
type="text"
class="form-control col-sm-1"
id="inputEmail"
placeholder="username#gmail.com"
/>
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>
You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

document.getElementById in amp-script code giving element data differently

I am using AMP to develop my website. In that, I am using amp-script. When I use document.getElementById, it is giving the element data differently. I am looking for some properties like value etc. in it. But, can't those. See the below screenshot to look at the contents.
Please help me solve this.
Thank you...
EDIT: Added code snippet
HTML:
<form action="click" target="_blank" name="contact_form" id="contact_form" class="contact-form__block">
<div class="form__group">
<label for="message" class="form__label message_label">The idea that is brewing in your mind?
*</label>
<textarea name="message" id="form__textarea" class="form__textarea"></textarea>
</div>
<div class="form__group">
<label for="name" class="form__label name_label">Name </label>
<input type="text" name="name" id="form__name" class="form__input name" value="" autocomplete="off">
</div>
<div class="form__groups">
<div class="form__group">
<label for="phone" class="form__label phone_label">Phone Number </label>
<input type="text" name="phone" id="form__phone" class="form__input phone" value=""
autocomplete="off">
<!-- error message start -->
<!-- <div class="form__error e_mail">Please enter all required details.</div> -->
<!-- error message end -->
</div>
<div class="form__group">
<label for="mail" class="form__label email_label">Email *</label>
<input type="text" name="mail" id="form__mail" class="form__input mail">
</div>
</div>
<div class="form__group">
<div class="form-button__block">
<button type="button" name="submit" class="form__submit" id="form-submit">
<div class="arrow__btn-link-text">Let's Connect</div>
<amp-img src="stroke-arrow-right.svg" height="1" width="1"
alt="arrow right icon" class="arrow__btn-icon">
</button>
<!-- <div class="button--border"></div> -->
</div>
<div class="error_box">
<span class="error_message"></span>
</div>
</div>
</form>
JS:
var form = document.getElementById("form-submit"), msg;
form.addEventListener("click", function(event) {
event.preventDefault();
if (document.getElementById('form__textarea').value == '') {
msg = false;
} else {
msg = true;
}
if (document.getElementById('form__mail').value == '') {
email = false;
} else {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var validEmail = emailReg.test(document.getElementById('form__mail').value);
if (!validEmail) {
email = false;
} else {
email = true;
}
}
if (document.getElementById('form__phone').value == '') {
phone = true;
document.getElementById('form__phone').value = "";
} else {
var phoneReg = /^([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
var validPhone = phoneReg.test(document.getElementById('form__phone').value);
if (!validPhone) {
phone = false;
} else {
phone = true;
}
}
if (document.getElementById('form__name').value == '') {
document.getElementById('form__name').value = "";
} else {
name = true;
}
if (!msg || !email || !phone) {
console.log("Error in formmmmmmmmmmmmm");
return false;
} else {
console.log("valid formmmmmmmmmmmmmmmmmmmmmm");
}
});

Trying to store a completed form into an array

I'm creating a registration page and am currently attempting to store the inputs of the form into an array. I'm using
var form_inputs = document.getElementsByClassName("form_input");
to store the inputs in the same place, however if I try to alert form_inputs to test if anything is actually being stored, it just alerts "Undefined".
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var form_inputs = document.getElementsByClassName("form_input");
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
console.log(form_inputs);
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input class="form_input" type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input class="form_input" type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input class="form_input" type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input class="form_input" type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input class="form_input" type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input class="form_input" type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
Array.from(document.getElementsByClassName("form_input")).forEach(
function(element, index, array) {
alert(element.innerHTML)
}
);
this will alert you of those elements

Form Validation using JavaScript?

I'm trying to use form validation using JavaScript, however I don't seem to get any response, not even an alert even though it's there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="2013.php" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>
use === or == for condition checking in javascript.
if(document.getElementById('name').value === ""){
alert("enter something valid");
return false;
}
You have to use == for comparison.= is used for assigment
if(document.getElementById('name').value == ""){
alert("enter something valid");
return false;
}
Working Demo
Here Your issue is regarding if condition only! You must use == OR === in JavaScript for comparison.
Below is corrected script!
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
If you remove Or avoid return false, form will postback Even if Validation fails! So, return false means, exiting from function after if is must, and which is missed out in another answer!!
You are using = that is assignment operator, use == comparison operator that's work fine
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
I can't believe I've never realised this until now, although if you attach your Javascript to the form submission event, instead of the button submit event; the normal browser verification works (ie. input[type="email], required="required", etc.).
Works in Firefox & Chrome.
// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
e.preventDefault();
console.log ("Submitted! Now serialise your form and AJAX submit here...");
})
I have done a better way to do form validation using bootstrap. You can take a look at my codepen http://codepen.io/abhilashn/pen/bgpGRw
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\#[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;
function initFormElements(sValidElems) {
var inputElems = document.getElementsByTagName('textarea');
for(var i = 0; i < inputElems.length; i++) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
/* Add the code for the input elements */
inputElems = document.getElementsByTagName('input');
for(var i = 0; i < inputElems.length; i++) {
if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
}
/* submit handler */
com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
/* Add the default focus handler */
document.getElementsByTagName('input')[0].focus();
/* Add the event handlers for validation */
com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}
function highlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = g_FocusBackColor;
}
}
function unHightlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = "";
}
}
function validateAddress() {
var formField = document.getElementById('address');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpAddress');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
}
return ok;
}
}
function validateFirstName() {
var formField = document.getElementById('firstName');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpfirstName');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
}
return ok;
}
}
function validateEmailAddress() {
var formField = document.getElementById('email');
var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
var grpEle = document.getElementById('grpEmail');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
}
}
return ok;
}
function validateCellPhone() {
var formField = document.getElementById('cellPhone');
var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
var grpEle = document.getElementById('grpCellPhone');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
}
}
return ok;
}
function validateAllfields(e) {
/* Need to do it this way to make sure all the functions execute */
var bOK = validateFirstName();
bOK &= validateEmailAddress();
bOK &= validateCellPhone();
bOK &= validateAddress();
if(!bOK) {
alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
com_abhi.EVENTS.preventDefault(e);
}
}
com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<h1 class="text-center">Interactive form validation using bootstrap</h1>
<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
<div id="grpfirstName" class="form-group">
<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
<span id="firstNameIcon" class=""></span>
<div id="firstNameErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
</div>
<div id="grpEmail" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<span id="EmailIcon" class=""></span>
<div id="emailErrorMsg" class="text-danger"></div>
</div>
</div>
<div id="grpCellPhone" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
<span id="cellPhoneIcon" class=""></span>
<div id="cellPhoneErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group" id="grpAddress">
<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
<div class="col-sm-10">
<textarea id="address" class="form-control"></textarea>
<span id="addressIcon" class=""></span>
<div id="addressErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div> <!-- End of row -->
</div> <!-- End of container -->
Please check my codepen to better understand code.

Categories