I would like it such that a user only has to sign-in once and then the next time they open the hybrid app the get signed in automatically. The JavaScript code below here works but only when I remove the 'login/submit' div () which I need. How can I get around this?
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
#chiboz in your javascript, instead of using:
document.EventConfirmRedirection.submit();
use:
$('#submit').click();
Related
I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});
I have a Login form that working fine. I tried to extend login action for adding extra features.
First I prevent the form to be submit when the submit button is clicked, I perform ajax request and finally if everything is correct I submit the form, but my form is not submitted until the submit button is clicked twice. What am I doing wrong?
HTML Part:
<div id="loginFormDiv">
<form class="form-horizontal" method="POST" action="index.php">
<input type="hidden" name="module" value="Users">
<input type="hidden" name="action" value="Login">
<div class="group"><input id="username" type="text" name="username" ><span class="bar"></span><label>Username</label></div>
<div class="group"><input id="password" type="password" name="password" ><span class="bar"></span><label>Password</label></div>
<div class="group"><button type="submit" class="button buttonBlue">Sign in</button></div>
</form>
</div>
JS Part:
jQuery.Class("ParsSecureLogin_Js", {}, {
checkLogin: function () {
var thisInstance = this;
var checkUserLogin = function (e) {
e.preventDefault();
var username = $('#username').val();
var user_pass = $('#password').val();
var theForm = $(this);
var url = 'index.php?module=ParsSecureLogin&parent=Settings&action=CheckLogin&_user=' + username + '&_pss=' + user_pass;
jQuery.ajax({
url: url
}).done(function (data) {
if (data == '' || data == 'undefined') {
alert('Unknown error. Please contact admin to check!');
return false;
} else {
theForm.unbind('submit').submit();
return true;
}
});
}
jQuery('#loginFormDiv').on("submit", checkUserLogin);
},
registerEvents: function () {
var thisInstance = this;
thisInstance.checkLogin();
}
});
jQuery(document).ready(function () {
var ParsSecureLogin = new ParsSecureLogin_Js();
ParsSecureLogin.registerEvents();
});
It is because #loginFormDiv is a <div> not a <form> change the selector to:
jQuery('#loginFormDiv form').on("submit", checkUserLogin);
Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">
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.