Regular Expression always false - javascript

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

You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

Related

Login Form- Not working if else statements

I cant get my login form to work with the separate logins, the preview wont event show up. I think there is something wrong with my if-else statements.
HTML:
<body ng-app="myApplication" ng-controller="myController" ng-cloak>
<h3>Contact Us</h3>
<div id="showDiv" ng-show="firstPage">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Enter your name" ng-model="name"><br>
<label for="email">Email:</label>
<input type="email" placeholder="Enter your email" ng-model="email"><br>
<label for="number">Number:</label>
<input type="number" placeholder="Enter your number" ng-model="phoneNumber"><br>
<label for="issue">Issue:</label>
<textarea name="issue" rows="5" cols="20" placeholder="Enter your issue" ng-model="issue"></textarea>
<br>
<br>
<input type="submit" value="Submit" id="submit" ng-click="showHide()">
<input type="reset" value="Reset" id="reset">
</form>
</div>
<div id="hideDiv" ng-show="secondPage">
<p ng-bind="feedback"></p>
<p>Your contact details are:</p>
<p>Email: <span ng-bind='email'></span></p>
<p>Phone Number: <span ng-bind='phoneNumber'></span></p>
<p>Your issue is:</p>
<p><span ng-bind='issue'></span></p>
<input type="submit" value="Go Back" id="goBack" ng-click="hideShow()" />
</div>
Javascipt:
<script>
angular.module('myApplication', []).controller('myController', function($scope){
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
$scope.firstPage = true;
$scope.secondPage = false;
$scope.showHide = function()
{
$scope.firstPage = false;
$scope.secondPage = true;
$scope.feedback = "";
if ($scope.name = "Po Lu" && $scope.email = "Po.Tom#acc.ac.au" && $scope.phonenumber = "021") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ;
}
else if ($scope.name == "Mel Tom" && $scope.email = "Mel.Tom#acc.ac.au" && $scope.phonenumber = "0217") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ;
}
else {
$scope.firstPage = true;
$scope.secondPage = false;
alert("Please Enter valid details");
}
}
$scope.hideShow = function()
{
$scope.firstPage = true;
$scope.secondPage = false;
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
}
});
</script>
Below are the mistakes made.
inside the if conditions, we should never use assignment =, but use conditional operators such as == or ===(strict type checking!)
Number type input won't allow zeros in the beginning, so I changed it from "021" to "21"
phoneNumber variable is set to phoneNumber in html, but in js its phonenumber so I changed it!
Finally I'm using double equals inside the if condition,so that type won't be an issue, we can compare number to string, if you want you can strictly check the types!
angular.module('myApplication', []).controller('myController', function($scope) {
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
$scope.firstPage = true;
$scope.secondPage = false;
$scope.showHide = function() {
$scope.firstPage = false;
$scope.secondPage = true;
$scope.feedback = "";
if ($scope.name == "Po Lu" && $scope.email == "Po.Tom#acc.ac.au" && $scope.phoneNumber == "21") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already.";
} else if ($scope.name == "Mel Tom" && $scope.email == "Mel.Tom#acc.ac.au" && $scope.phoneNumber == "217") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already.";
} else {
$scope.firstPage = true;
$scope.secondPage = false;
alert("Please Enter valid details");
}
}
$scope.hideShow = function() {
$scope.firstPage = true;
$scope.secondPage = false;
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<div ng-app="myApplication" ng-controller="myController" ng-cloak>
<h3>Contact Us</h3>
<div id="showDiv" ng-show="firstPage">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Enter your name" ng-model="name"><br>
<label for="email">Email:</label>
<input type="email" placeholder="Enter your email" ng-model="email"><br>
<label for="number">Number:</label>
<input type="number" placeholder="Enter your number" ng-model="phoneNumber"><br>
<label for="issue">Issue:</label>
<textarea name="issue" rows="5" cols="20" placeholder="Enter your issue" ng-model="issue"></textarea>
<br>
<br>
<input type="submit" value="Submit" id="submit" ng-click="showHide()">
<input type="reset" value="Reset" id="reset">
</form>
</div>
<div id="hideDiv" ng-show="secondPage">
<p ng-bind="feedback"></p>
<p>Your contact details are:</p>
<p>Email: <span ng-bind='email'></span></p>
<p>Phone Number: <span ng-bind='phoneNumber'></span></p>
<p>Your issue is:</p>
<p><span ng-bind='issue'></span></p>
<input type="submit" value="Go Back" id="goBack" ng-click="hideShow()" />
</div>
</div>

How to check for required radio and checkbox inputs in a form and then display a message if they're checked or unchecked?

I implemented some user feedback for users. If required fields are empty, some error messages will appear to alert users that the inputs are empty.
I have been working all weekend on this. I get the correct feedback for empty 'text' values. I'm having a hard time checking for empty checkbox and radio inputs. By default, when you click submit/check, you get the correct error message for empty 'text' fields but not radio and checkbox items.
My code:
HTML
<form id="my-form" class="form" action="/" method="post">
<div class="form-row">
<label for="name" class="form-label">Name *</label>
<div class="form-field">
<input id="name" name="name" placeholder="Please enter your name" type="text" required>
</div>
</div>
<div class="form-row">
<label for="email" class="form-label">Email *</label>
<div class="form-field">
<input id="email" name="email" placeholder="Please enter your email address" type="email" required>
</div>
</div>
<div class="form-row">
<label for="radio" class="form-label">Radio Buttons *</label>
<div class="form-field">
<span class="form-radios">Select 1: </span>
<input id="radio" name="radiobutton" value="selection-one" type="radio" required>
<span class="form-radios">Select 2: </span>
<input name="radiobutton" value="selection-two" type="radio">
</div>
</div>
<div class="form-row">
<label for="checkbox" class="form-label">Checkboxes *</label>
<div class="form-field">
<span class="form-radios">Select 1: </span>
<input id="checkbox1" name="checkbox" type="checkbox" value="checkbox1value" required>
<span class="form-radios">Select 2: </span>
<input id="checkbox2" value="checkbox2value" name="checkbox" type="checkbox">
</div>
</div>
<div class="form-row">
<label for="tel" class="form-label">Telephone *</label>
<div class="form-field">
<input id="tel" name="telephone" placeholder="Please enter your number" type="tel" required>
</div>
</div>
<div class="form-row">
<label for="website" class="form-label">Website *</label>
<div class="form-field">
<input id="website" name="website" placeholder="Begin with https://" type="url" required>
</div>
</div>
<div class="form-row">
<label for="message" class="form-label">Message *</label>
<div class="form-field">
<textarea id="message" name="How long were you away for?" placeholder="Include all the details you can" required></textarea>
</div>
</div>
<div class="form-row">
<button id="check" name="submit" type="submit" class="form-submit">Send Email</button>
</div>
</form>
JAVASCRIPT
const requiredElements = document.getElementById("my-form").querySelectorAll("[required]"),
submitButton = document.getElementById("check"),
errorMsgOutput = document.getElementById("output");
submitButton.addEventListener("click", function() {
var errorMsg = "";
var radios = document.getElementById("my-form").radiobutton;
var checboxes = document.getElementById("my-form").checbox;
for (var i = 0; i < requiredElements.length; i++) {
var form = requiredElements[i];
// Checking for empty text fields
if (form.value.length) {
errorMsg += form.name + ": " + "Filled" + "<br>";
} else if (form.value.length === 0) {
errorMsg += form.name + ": " + "Not Filled" + "<br>";
}
// My attempt to check that radio values are filled. By default, the error message says that it's checked ('filled') even when it's not.
// for(var j = 0, k = radios.length; j < k; j++){
// if (form.type == 'radio' && radios[k].checked) {
// errorMsg += form.name + ": " + "Filled" + "<br>";
// } else {
// errorMsg += form.name + ": " + "Not Filled" + "<br>";
// }
// }
}
errorMsgOutput.innerHTML = errorMsg;
});
Even before you click the send email button, the checkbox and radio inputs display the 'filled' error message. See: https://jsfiddle.net/krisixco/zgdf2sec/10/ to see what I mean...
It seems to me that you ask two questions. The first is why the required does not display a pop-up for radio and checkbox and the second is how to check if they were filled in or not by javascript.
About the first question, in the code you put in your question, the checkbox and radio inputs do not have the required attribute
For the second question use the checked method
example:
let checkbox = document.querySelector('input[type=checkbox]')
if(checkbox.checked){
// checked
else {
// not checked
}
for (var i = 0; i < requiredElements.length; i++) {
var form = requiredElements[i];
// Checking for empty text fields
if(form.name === "radiobutton" || form.name === "checkbox" ){
if(!form.checked) errorMsg += form.name + ": " + "Not Filled" + "<br>";
if(form.checked) errorMsg += form.name + ": " + "Filled" + "<br>";
} else{
if (form.value.length) {
errorMsg += form.name + ": " + "Filled" + "<br>";
} else if (form.value.length === 0) {
errorMsg += form.name + ": " + "Not Filled" + "<br>";
}
}

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

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

How to get this form validation script working

I have created a form and a form validation script that checks if all fields are filled in, the name and city fields contain only letters, the age and phone fields contain only numbers and if the entered email is a valid one. When used in the console, all of the statements work, but when I fill in every field, or fill in invalid values in the email field or phone number and age field, I still get an error message saying that the name and city field must contain only letters.
I have tried writing out every statement alone and also checking them one by one.
HTML & JS
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$(".btn.btn-primary.submit").click(function () {
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
})
});
</script>
When I leave all fields empty the warning is ok. But when I do anything else I only get the warning that I can only use letters in the fields Name and City.
All help is greatly appreciated for a beginner!
I think you are failing to reassign the variables outside of the onClick function. I have tested below code and it works for me, i admit it is probably not a perfect solution reassigning all the variables each time and perhaps you could place some in global scope such as the RegEx statements. I also removed the loop as i don't think you need to loop over everything 5 times to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
$(".btn.btn-primary.submit").click(function () {
let name_cityRegex = /^[a-zA-Z]+$/;
let emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
let age_phoneRegex = /^\d+$/;
let nameValue = $('#inputName').val();
let cityValue = $('#inputCity').val();
let ageValue = $('#inputAge').val();
let phoneValue = $('#inputPhone').val();
let nameResult = name_cityRegex.test(nameValue);
let cityResult = name_cityRegex.test(cityValue);
let ageResult = age_phoneRegex.test(ageValue);
let phoneResult = age_phoneRegex.test(phoneValue);
let mailValue = $('#InputEmail').val();
let mailResult = emailRegex.test(mailValue);
if (nameValue == '' || cityValue == '' || ageValue == '' || phoneValue == '' || mailValue == '') {
$('.alert.alert-danger').show();
}
else if (nameResult === false || cityResult === false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
// })
});
</script>
</body>
</html>
I don't really know why your tests gives you an error, but I think your $('.form-control').each is useless.
In this foreach you test all your fields for each field.
Maybe try without this foreach, just test all your fields when you click on the button by removing this bit of code :
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
})
I don't see any other problem.
You have a syntax error I corrected that check below code.
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" name="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" name="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" name="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="text" name="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="text" name="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit" onClick="validateForm()">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>

Form Validation using JavaScript?

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

Categories