I want to Remove glyphicon-ok from Submit button - javascript

I am working on a Registration Form. I have applied Jquery with the help of ID of the element. When I click the submit button I also got glyphicon-ok at submit button, whick i dont want to happen. Simply copy the code and past it in html file on your PC....
<html>
<head>
<title>Form Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function validateText(id)
{
if($("#"+id).val()==null || $("#"+id).val()=="")
{
var div = $("#"+id).closest("div");
div.removeClass("has-success");
$("#glypcn"+id).remove();
div.addClass("has-error has-feedback");
div.append('<span id="glypcn'+id+'" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>')
return false;
}
else
{
var div = $("#"+id).closest("div");
div.removeClass("has-error");
div.addClass("has-feedback has-success");
$("#glypcn"+id).remove();
div.append('<span id="glypcn'+id+'" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>')
return true;
}
}
$(document).ready(function ()
{
$("#btn1").click(function ()
{
validateText("firstname");
validateText("lastname");
validateText("username");
validateText("password");
validateText("cpassword");
validateText("date");
validateText("male");
validateText("female");
$("register-form").submit();
});
}
);
</script>
<!-- Latest compiled and minified CSS -->
<script src="static/jquery-3.1.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!--<script src="C:/Users/DA_YALS/Desktop/fv/static/combodate.js" type="text/javascript"></script>-->
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6" style="height:auto; border:solid black;">
<form method="post" role="form" id="register-form" autocomplete="off">
<div class="form-group">
<label for="firstname">First Name:</label>
<input class="form-control" id="firstname" placeholder="First Name" type="text" required="required">
</div>
<div class="form-group">
<label for="lastname">Last Name:</label>
<input class="form-control" id="lastname" placeholder="Last Name" type="text" name="lastname" required="required" >
</div>
<div class="form-group">
<label for="username">Username:</label>
<input class="form-control" placeholder="Username" type="text" id="username" name="username" required="required">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input class="form-control" placeholder="Password" type="password" id="password" name="password" required="required">
</div>
<div class="form-group">
<label for="cpassword">Confirm Password:</label>
<input class="form-control" placeholder="Password" type="password" id="cpassword" name="cpassword" required="required">
</div>
<div class="form-group">
<label for="date" id="text">Date of Birth:</label>
<input class="form-control" type="text" id="date" name="date" data-format="DD-MM-YYYY" data-template="D MMM YYYY" name="date" value="09-01-2013" required="required">
</div>
<div class="form-group" style="border: solid;">
<label id="gender">Gender:</label>
<label class="radio-inline"><input id="male" type="radio" name="Male" checked>Male</label>
<label class="radio-inline"><input id="female" type="radio" name="Female">Female</label>
</div>
<div class="form-group" >
<button class="btn btn-success" id="btn1" type="submit">Submit</button>
</div>
</form>
</div>
<div class="col-lg-3">
</div>
</div>
</div>
</body>
</html>

The icon is not applied on the submit buttons but on the radios.
So you have to modify your validateText function to not add the icon on radio buttons:
function validateText(id)
{
if($("#"+id).val()==null || $("#"+id).val()=="")
{
var div = $("#"+id).closest("div");
div.removeClass("has-success");
$("#glypcn"+id).remove();
div.addClass("has-error has-feedback");
if (!($("#"+id).is(':checkbox') || $("#"+id).is(':radio'))) {
div.append('<span id="glypcn'+id+'" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
}
return false;
}
else
{
var div = $("#"+id).closest("div");
div.removeClass("has-error");
div.addClass("has-feedback has-success");
$("#glypcn"+id).remove();
if (!($("#"+id).is(':checkbox') || $("#"+id).is(':radio'))) {
div.append('<span id="glypcn'+id+'" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
}
return true;
}
}

Related

page redirect after success bootstrap validation without using php

Team,
I am trying to redirect after success form validation. If it is not success it has to be there in same page if it is success it has to redirect other page
I have added below line after was class validated code
$(location).attr('href', 'data.html');
it is redirecting to next page but I am not seeing any error message I am missing some valdiation.
Here is my entire code.
$(function () {
'use strict'
$('#data_input').on('submit', function (event) {
if (!event.target.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
$(location).attr('href', 'data.html');
return true;
});
$("#resetbtn").on("click", function (event) {
event.preventDefault();
$('#data_input')
.trigger("reset")
.removeClass('was-validated')
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<form class="requires-validation" id="data_input" method="post" novalidate>
<div class="form-group row">
<div class="col">
<label> Name</label> <input type="text" class="form-control" name="projectName" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col">
<label>Code</label> <input type="text" class="form-control" name="projectCode" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col">
<label>Number</label> <input class="form-control" type="text" name="sprintNumber" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col"> <label>Start Date:</label> <input type="text" class="form-control has-feedback-left" id="fromdate" placeholder="Please Enter Start Date" name="fromdate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col"> <label>End Date:</label> <input type="text" class="form-control has-feedback-left" id="todate" placeholder="Please Enter End Date" name="todate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<!--<div class="form-group row">
<div class="col">
<label>Total Days</label> <input type="text" class="form-control has-feedback-left"
name="numberdays" id="numberdays" disabled>
</div>
</div>-->
<br />
<button id="submit" type="submit" class="btn btn-primary">Next</button>
<button id="resetbtn" type="button" class="btn btn-secondary">Clear</button>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
Please let me know what I am doing wrong here
in your event submit. You use a validation if statement (checkvalidity).
$('#data_input').on('submit', function (event) {
**if (!event.target.checkValidity()) {**
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
**$(location).attr('href', 'data.html');**
return true; ...
but whether it is valid or not you still perform the location redirect afterwards.
the redirect should be placed in a if instead you will always be redirected before any validation.

Bootstrap 4 confirm password validation not working

Im using bootstrap 4 form. any one know how to add correctly passwords doesn't match validation.
Thanks
// Check if passwords match
$('#pwdId, #confirmPassword').on('keyup', function () {
if ($('#newPassword').val() != '' && $('#confirmPassword').val() != '' && $('#confirmPassword').val() == $('#confirmPassword').val()) {
}
});
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<form class="form-signin needs-validation" novalidate><div class="card shadow-sm">
<div class="card-body">
<div class="form-group">
<label class="sr-only" for="oldPassword">Current Password</label>
<input class="form-control form-control-sm" id="oldPassword" name="password" placeholder="Current Password"
required
type="password" autocomplete="off" aria-describedby="inputGroupPrepend">
<div class="invalid-feedback">
Please enter current password.
</div>
</div>
<div class="form-group">
<div class="form-group">
<label class="sr-only" for="newPassword">New Password</label>
<div class="input-group">
<input type="password" autocomplete="off" class="form-control form-control-sm" id="newPassword" placeholder="New Password" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please enter new password.
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="confirmPassword">Confirm Password</label>
<div class="input-group">
<input type="password" autocomplete="off" class="form-control form-control-sm" id="confirmPassword" placeholder="Confirm Password" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Password not a match.
</div>
</div>
</div>
<button id="submitBtn" class="btn btn-md btn-primary btn-block" type="submit">Update</button>
</div></div>
</form>
You need to add one line of code into the opening form tag.
<form class="form-signin needs-validation" novalidate oninput='confirmPassword.setCustomValidity(confirmPassword.value != newPassword.value ? true : false)'>
I have made a codepen. Please check that.
https://codepen.io/subhojitghosh/pen/JjROMLO
Reference: https://stackoverflow.com/a/53065577/10850734
I simplified your validation logic and used disabled and hidden HTML's attributes. You can see the refactored code working here in codesandbox
JS code:
// To ensure the following JS code is executed when the DOM is ready to be manipulated by JS
$(document).ready(function () {
$("#newPassword, #confirmPassword").on("keyup", function () {
// store the `newPassword` and `confirmPassword` in two variables
var newPasswordValue = $("#newPassword").val();
var confirmPasswordValue = $("#confirmPassword").val();
if (newPasswordValue.length > 0 && confirmPasswordValue.length > 0) {
if (confirmPasswordValue !== newPasswordValue) {
$("#password-does-not-match-text").removeAttr("hidden");
$("#submitBtn").attr("disabled", true);
}
if (confirmPasswordValue === newPasswordValue) {
$("#submitBtn").removeAttr("disabled");
$("#password-does-not-match-text").attr("hidden", true);
}
}
});
});
and slightly changed your HTML to this:
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous"
/>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"
></script>
<script src="./index.js"></script>
<form class="form-signin needs-validation" novalidate>
<div class="card shadow-sm">
<div class="card-body">
<div class="form-group">
<label class="sr-only" for="oldPassword">Current Password</label>
<input
class="form-control form-control-sm"
id="oldPassword"
name="password"
placeholder="Current Password"
required
type="password"
autocomplete="off"
aria-describedby="inputGroupPrepend"
/>
<div class="invalid-feedback">Please enter current password.</div>
</div>
<div class="form-group">
<div class="form-group">
<label class="sr-only" for="newPassword">New Password</label>
<div class="input-group">
<input
type="password"
autocomplete="off"
class="form-control form-control-sm"
id="newPassword"
placeholder="New Password"
aria-describedby="inputGroupPrepend"
required
/>
<div class="invalid-feedback">Please enter new password.</div>
</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="confirmPassword">Confirm Password</label>
<div class="input-group">
<input
type="password"
autocomplete="off"
class="form-control form-control-sm"
id="confirmPassword"
placeholder="Confirm Password"
aria-describedby="inputGroupPrepend"
required
/>
<div class="invalid-feedback">Password not a match.</div>
</div>
</div>
<p id="password-does-not-match-text" class="text-danger" hidden>
Your new password does not match
</p>
<button
id="submitBtn"
class="btn btn-md btn-primary btn-block"
type="submit"
disabled
>
Update
</button>
</div>
</div>
</form>

In this code javascript validation is not working

How it will work? I want to know how javascript connect with html and div tag is correct. I didn't get which code is doing mistake.
<script type="text/javascript">
function validate()
{
if (document.myForm.name.value="") {
alert("should be fill");
document.myForm.name.focus();
return false;
}
return(true);
}
</script>
.container{background-color:gray;
width:550px;
height:650px;
align-content:center;
background: rgba(255, 255, 255, 0.1);}
h1{text-align:center;
color:darkslategray;
text-decoration-line:underline;}
input{width:100%}
#button{text-align:right;}
body {background-image:url("bg1.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css\bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css\custom.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<title>
login form
</title>
</head>
<body>
<div class="container">
<form method="post" name="myForm" onsubmit="return(validate());" data-toggle="validator">
<div class="form-group">
<h1><b><u>
Create an account
</u>
</h1>
<div class="row">
<div class="col-md-6">
First Name:
<input type="text" name="name" id="" value="" placeholder="First Name">
<span id="fnameerror" class="text-danger">
</span>
</div>
<div class="col-md-6">
Last Name:
<input type="text" name="lastname" id="lastname" placeholder="Last Name" >
<span id="lnameerror" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
Company Name:
<input type="text" name="companyname" id="" placeholder="Company Name">
<span id="" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
Street address:
<input type="text" name="streetaddress" id="address" placeholder="Street address">
<span id="adderror" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
Town/City:
<input type="text" name="city" id="city" placeholder="Town/City">
<span id="cityerror" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
State/Country:
<input type="text" name="state" id="state" placeholder="State/Country">
<span id="stateerror" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
Postcode/Zip:
<input type="text" name="zip" id="zip" placeholder="Postcode/Zip">
<span id="ziperror" class="text-danger">
</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
Phone:
<input type="text" name="Phone" id="phone" placeholder="Phone">
<span id="pherror" class="text-danger">
</span>
</div>
<div class="col-md-6">
Email:
<input type="emaill" name="Email" id="email" placeholder="Email">
<span id="emailerror" class="text-danger">
</span>
</div>
</div>
<div class="row">
<div class="col-md-1">
<input type="checkbox" name="checkbox" id="box" placeholder="">
<span id="boxerror" class="text-danger">
</span>
</div>
<div class="col-md-11">
Create an account
</div>
</div>
<div class="row" id="button">
<div class="col-md-12">
<button type="submit" value="submit">
<b>SignUp</b>
</button>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
you are using assignment operator in if (document.myForm.name.value = "")
Try with this code
function validate() {
if (document.forms["myForm"]["name"].value == "") {
alert("should be fill");
document.myForm.name.focus();
return false;
}
return (true);
}
You have missed equals to == in your comparison. For comparison is should be == double equals. Change it and it should work.
if (document.myForm.name.value == "") {
...
}
It seems that you haven't added the js file in the html file. Add the js file just above ending the body tag.
<script type="text/javascript" src="location to the file"><script>
Moreover in update the js code with:
function validate(e) {
e.preventDefault();
console.log(document.myForm.name.value);
if (document.myForm.name.value == "") {
alert("should be fill");
document.myForm.name.focus();
}
}
You also need to modify the form element.
<form method="post" name="myForm" onsubmit="validate(event);" data-toggle="validator">

Cannot align bootstrap submit button in form?

I have used bootstrap form but submit button is not getting aligned below Name and Number field in form. I tried to use various css styles but could not align it. See screenshot submit button is not aligned properly.
In app.js:
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactlist").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`
<form>
<div class="form-group">
<label for="InputName">Name</label>
<input type="text" class="form-control" id="inputName" aria-describedby="namehelp" placeholder="Enter Name ">
</div>
<div class="form-group">
<label for="InputNumber">Number</label>
<input type="text" class="form-control" id="inputNumber" placeholder="Enter Number">
</div>
<div class="form-group">
<label for="InputGroup">Group</label>
<input type="text" class="form-control" id="inputGroup" placeholder="Enter Group">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
`;
}
In index.css:
.form-group{
padding-left: 30px;
padding-right: 30px;
}
.form .btn-primary{
padding-left: 30px;
}
I also tried to wrap submit button inside div tag but still no effect.
form .btn-primary{
margin-left: 30px;
}
not .form this should also be margin otherwise the text would be shifted 30 pixels but the button remain in the same place
Instead of adding padding to .form-group and .btn what you can do is add padding to the form itself, just add a class to the form and add css against it.
Working example -
function editContact(id) {
document.getElementById("editcontact").innerHTML =
`
<form class="form">
<div class="form-group">
<label for="InputName">Name</label>
<input type="text" class="form-control" id="inputName" aria-describedby="namehelp" placeholder="Enter Name ">
</div>
<div class="form-group">
<label for="InputNumber">Number</label>
<input type="text" class="form-control" id="inputNumber" placeholder="Enter Number">
</div>
<div class="form-group">
<label for="InputGroup">Group</label>
<input type="text" class="form-control" id="inputGroup" placeholder="Enter Group">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
`;
}
editContact(1);
.form{
padding: 0 30px;
}
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
<div id="editcontact">
</div>
</body>
</html>
Notice, I added .form class, and adding to it.
Here is a plunker of the above snippet https://plnkr.co/edit/R2ku3opNtn3KsBDYKYr3?p=preview
wrap button inside form-group div (new ) P.S try this snippet in expanded snippet view
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<label for="InputName">Name</label>
<input type="text" class="form-control" id="inputName" aria-describedby="namehelp" placeholder="Enter Name ">
</div>
<div class="form-group">
<label for="InputNumber">Number</label>
<input type="text" class="form-control" id="inputNumber" placeholder="Enter Number">
</div>
<div class="form-group">
<label for="InputGroup">Group</label>
<input type="text" class="form-control" id="inputGroup" placeholder="Enter Group">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>

form validation in bootstrap 3

I have a form in bootstrap 3. I am able to do basic validation with the has-error class. How do l check for specific user inputs like?
The user can only enter characters as first name and last name
The user can only enter numbers /digits as telephone number
The user can only enter valid email characters.
And also how can l output a more user friendly validation error messages.
I'm new to bootstrap and any help is greatly appreciated. Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form method="post" id="contactform" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" placeholder="Email" name="email" type="text" id="email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" placeholder="Phone Number" name="phone" type="text" id="phone" />
</div>
</div>
<button type="button" id="contactbtn" class="btn btn-
primary">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function validateText(id) {
if ($("#" + id).val() == null || $("#" + id).val() == "") {
var div = $("#" + id).closest("div");
div.addClass("has-error");
return false;
} else {
var div = $("#" + id).closest("div");
div.removeClass("has-error");
return true;
}
}
$(document).ready(
function() {
$("#contactbtn").click(function() {
if (!validateText("firstname")) {
return false;
}
if (!validateText("lastname")) {
return false;
}
if (!validateText("email")) {
return false;
}
if (!validateText("phone")) {
return false;
}
$("form#contactform").submit();
});
}
);
</script>
</body>
</html>
HTML input fields have an attribute called pattern which you can use for ensuring a specific input with a regex.
<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Last Name" name="lastname"
type="text" id="lastname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Email" name="email"
type="text" id="email" pattern="^[^#\\s]+#[^#\\s]+\\.[^#\\s]+$" />
...
<input class="form-control" placeholder="Phone Number" name="phone"
type="text" id="phone" pattern="^\d*$" />
That's just a simple sample e-mail regex. There are lot of other regex for e-mails.
You can use jquery boostrap validation.It's much easy.you can follow following
answer
A combination of using the correct input type as well as declaring a pattern attribute can likely preclude the need for any special JavaScript.
1) The user can only enter characters as first name and last name
For this you need to rely on <input type="text"> which by default allows basically anything. So we'll need to apply a pattern that restricts this field to only letters:
<input type="text" pattern="[A-Za-z]+">
2) The user can only enter numbers /digits as telephone number
Depending on your needs this could be as simple as using the correct input type:
<input type="tel">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel
Because different countries have different patterns you may want to improve this with the addition of a pattern attribute.
<input type="tel" pattern="^[0-9\-\+\s\(\)]*$">
This will allow your number inputs to be a bit more flexible, accept dashes and parenthesis, allow the user to specify a +DIGIT country code, etc.
3) The user can only enter valid email characters.
Again using the correct input type will greatly simplify your validation efforts:
<input type="email">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email
This is another one that can be a little 'fuzzy' when you're comparing certain input types as it really just looks for handle#domain.extension. You can read more about its specific validation patterns using the above link to Mozilla's developer toolkit.
You might have to tweak things if you want to use something else. But this is preferably used in bootstrap way.
var showErrorSuccess = function(element, status) {
if (status === false) {
element.parent().next().removeClass('hidden').parent().addClass('has-error');
return false;
}
element.parent().next().addClass('hidden').parent().removeClass('has-error').addClass('has-success');
};
var validate = function() {
event.preventDefault();
//validate name
var name = $('#firstname').val();
if (name.length < 3) {
return showErrorSuccess($('#firstname'), false);
}
showErrorSuccess($('#firstname'));
var lastname = $('#lastname').val();
if (lastname.length < 3) {
return showErrorSuccess($('#lastname'), false);
}
showErrorSuccess($('#lastname'));
//validate email
var email = $('#email').val(),
emailReg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if (!emailReg.test(email) || email == '') {
return showErrorSuccess($('#email'), false);
}
showErrorSuccess($('#email'));
//validate phone
var phone = $('#phone').val(),
intRegex = /[0-9 -()+]+$/;
if ((phone.length < 6) || (!intRegex.test(phone))) {
return showErrorSuccess($('#phone'), false);
}
showErrorSuccess($('#phone'));
};
body>form {
padding-left: 15px;
padding-top: 15px;
padding-right: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form class="form-vertical" method="post" id="contactform" onSubmit="javascript:validate()" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
</div>
<p class="help-block hidden">Please enter a name 3 characters or more.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
</div>
<p class="help-block hidden">Please enter a name 3 characters or more.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" name="email" placeholder="Email" type="email" id="email" />
</div>
<p class="help-block hidden">Please enter a valid email address.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" name="phone" placeholder="Phone Number" type="phone" id="phone" />
</div>
<p class="help-block hidden">Please enter a valid phone number.</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Here is easy and best concept to use form validation by using custom jquery/javascript code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form method="post" id="contactform" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname"
type="text" id="lastname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" name="email" placeholder="Email" type="email" id="email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" name="phone" placeholder="Phone Number"
type="phone" id="phone" />
</div>
</div>
<button type="button" id="contactbtn" onclick="validateText();" class="btn btn-
primary">Submit</button>
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function validateText(id){
//validate name
var name = $('input[id="firstname"]').val();
if (name.length < 3)
{
alert('Please enter a name 3 characters or more.');
return false;
}
var lastname = $('input[id="lastname"]').val();
if (name.length < 3)
{
alert('Please enter a name 3 characters or more.');
return false;
}
//validate email
var email = $('input[id="email"]').val(),
emailReg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if(!emailReg.test(email) || email == '')
{
alert('Please enter a valid email address.');
return false;
}
//validate phone
var phone = $('input[id="phone"]').val(),
intRegex = /[0-9 -()+]+$/;
if((phone.length < 6) || (!intRegex.test(phone)))
{
alert('Please enter a valid phone number.');
return false;
}
}
</script>
</body>
</html>

Categories

Resources