form validation in bootstrap 3 - javascript

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>

Related

How to trigger default Bootstrap 4 form validation error message from custom external script

In our contact form, I'm trying to only allow submissions from email addresses from the United States, since we can only do business in that one country. How can I trigger the default error message when a form submit attempt is made, so that "invalid" message appears the same way it appears for the first name and last name fields?
In the code below, for the sake of example, I'm allowing only 'com', 'edu', 'gov', 'net', 'org'. The goal is to trigger a message whenever an email address other than those above is entered into the email field.
$(document).ready(function() {
$(function() {
$("#testform").submit(function() {
str = $('input[name=emailAddress]').val();
str = str.split('#').slice(0);
str = str[1].split('.').slice(0);
var allowedDomains = ['com', 'edu', 'gov', 'net', 'org'];
alert("str = " + str[1]);
if ($.inArray(str[1], allowedDomains) !== -1) {
alert(str + ' is allowed');
} else {
alert('not allowed');
event.preventDefault();
event.stopPropagation();
$('#emailAddress').addClass('invalid');
}
});
});
});
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/holder.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/dist/js/bootstrap.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/popper.min.js"></script>
<div class="container">
<form action="" method="post" target="" class="needs-validation" role="form" id="testform">
<fieldset>
<div class="form-group">
<label for="firstName" class="col-form-label">Customer first name:
<input type="text" class="form-control" name="firstName" id="firstName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="lastName" class="col-form-label">Customer last name:
<input type="text" class="form-control" name="lastName" id="lastName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="emailAddress" class="col-form-label">Customer email address:
<input type="email" class="form-control" name="emailAddress" id="emailAddress" required placeholder="Enter valid email" aria-required="true">
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
</div>

javascript checking for blank for phonenumber and address

Please help me, I'm stuck.
Why doesn't the JavaScript below work? The script is checking if phone number and address is empty, but when the phone number and address field is entered, the alert still pops out.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
function checkingIsEmpty() {
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
I'd agree with #Madara's comment, that you should... just add required attribute on form inputs which are required and let the browser do the work for you
However, I believe the reason your code is not working is because you appear to be setting the const values of phone and address on entry to the screen... and then you're checking that initial value (rather than the latest value).
Instead you need to get the latest value from the controls as part of the function...
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value ==''){
alert("Please insert your address");
return false;
}
return true;
}
(Minor edit, you also need to return true at the end of your function, otherwise your submit won't work)
simplest way is to check if (!phoneInput.value) { ... }
as empty string and null will return falsy value
The problem you are having is because you are assigning the value of the fields at the time the page loads. Not at the time the function is called on submit. If you move the variable assignment into the function it should work for you.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
function checkingIsEmpty(){
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
return false;//for the example I don't want it to submit
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
You need to include the document.getElementById in your conditionals. Also, I would wrap both conditionals (Phone and Address) in another conditional so you can add classes for error styling on errored fields.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
var phone = document.getElementById("phoneNumberInput").value;
var address = document.getElementById("addressInput").value;
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == '' || document.getElementById("addressInput").value == '') {
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value == ''){
alert("Please insert your address");
return false;
}
} else {
alert('success');
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
The values of inputs are stored inside a constant, not a variable.
When page is loaded, the script is executed and the contents of actual inputs are stored.
When you're calling checkingIsEmpty() the values aren't refreshed.
I suggest you to get the value inside the checkingIsEmpty() function if you want to keep checking with javascript, but as suggested Madara in comments, you can use the required attribute <input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber" required>.
Checking inputs with required attribute or javascript is nice, but you have to check it server-side too. It's easy to press F12 and edit dom.
function checkingIsEmpty()
{
let phone = document.getElementById("phoneNumberInput").value;
let address = document.getElementById("addressInput").value;
if (phone == '')
{
alert("Please insert your phone number");
return (false);
}
if (address == '')
{
alert("Please insert your address");
return (false);
}
return (true); //You forgot to return true in case of your form is validated
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

I want to Remove glyphicon-ok from Submit button

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

JQuery code I wrote stopped working, is there anywrong I've overlooked?

For the below code I want the content of the submit button with the .btn-primary attribute to change to "Success!" only if the input fields are all not null.
At preset the code goes straight to success when the button is press whether or not the fields have content.
I thought it might be because the fields may somehow already have a value that is not null so I ran this code: alert($('#Comment').attr("value")); and it returned undefined in the alert message. Undefined is the same as null in js/jquery isn't it?
I got this code to work earlier and it was typed almost the same way with just a few changes. I undid the changes but it still does not work.
Any help will be appreciated. (If anyone knows this) Are there instances in which the same code could not work at a different time, all things being equal?
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
$(document).ready(function () {
var Fname = $('#FirstName').attr("value");
var Lname = $('#LastName').attr("value");
var Email = $('#Email').attr("value");
var Comment = $('#Comment').attr("value");
$(".btn-primary").click(function () //This block should say, if all fields are not null changed the content of button to "Success!" and change the content of <h1> to "THANKS, I'VE GOT YOUR MESSAGE."
{
if (Fname != null && Lname != null && Email != null && Comment != null)
{
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
</script>
And this is the html on the same page
<form class="form-horizontal" role="form" action="/Home/Contact" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName"/>
<span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com"/>
<span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea>
<span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>
When your document loads you are storing the value of Fname, Lname ..... so on. The issue is you then use these values in your conditional test but the values will not have changed as they are just the raw value from the first time the page loaded. One quick fix would be to bring these inside the click so on every click they can re evaluated
Also when checking you are only checking for null but these are not going to equal null anyway. Better would be to fully validate them or just test for generic truthy which excludes the falsy values such as null, undefined, empty string
$(document).ready(function () {
$(".btn-primary").click(function (e)
{
var Fname = $('#FirstName').val();
var Lname = $('#LastName').val();
var Email = $('#Email').val();
var Comment = $('#Comment').val();
//ADDED JUST TO STOP THE FORM SUBMITTING
e.preventDefault();
//very quick test but this could be a lot more detailed for true validation on each field
if (Fname && Lname && Email && Comment) {
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
<form class="form-horizontal" role="form" action="#" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName" /> <span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com" /> <span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea> <span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>

Categories

Resources