How to alert user for blank form fields? - javascript

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>

Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.

You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>

Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Javascript validation - group validation - if one entered, then all required

Using just jQuery (not validation plugin) I have devised a way to do a "if one, then all" requirement, but it's not at all elegant.
I'm wondering if someone can come up with a more elegant solution? This one uses some loop nesting and I'm really not pleased with it.
if ($("[data-group]")) {
//Store a simple array of objects, each representing one group.
var groups = [];
$("[data-group]").each(function () {
//This function removes an '*' that is placed before the field to validate
removeCurError($(this));
var groupName = $(this).attr('data-group');
//If this group is already in the array, don't add it again
var exists = false;
groups.forEach(function (group) {
if (group.name === groupName)
exists = true;
});
if (!exists) {
var groupElements = $("[data-group='" + groupName + "']");
var group = {
name: groupName,
elements: groupElements,
trigger: false
}
group.elements.each(function () {
if (!group.trigger) {
group.trigger = $(this).val().length !== 0;
}
});
groups.push(group);
}
});
//Now apply the validation and alert the user
groups.forEach(function (group) {
if (group.trigger) {
group.elements.each(function () {
//Make sure it's not the one that's already been filled out
if ($(this).val().length === 0)
// This function adds an '*' to field and puts it into a
// a sting that can be alerted
appendError($(this));
});
}
});
You don't have to store the groups in an array, just call the validateGroups function whenever you want to validate the $elements. Here is a working example http://jsfiddle.net/BBcvk/2/.
HTML
<h2>Group 1</h2>
<div>
<input data-group="group-1" />
</div>
<div>
<input data-group="group-1" />
</div>
<h2>Group 2</h2>
<div>
<input data-group="group-2" value="not empty" />
</div>
<div>
<input data-group="group-2" />
</div>
<div>
<input data-group="group-2" />
</div>
<button>Validate</button>
Javascript
function validateGroups($elements) {
$elements.removeClass('validated');
$elements.each(function() {
// Return if the current element has already been validated.
var $element = $(this);
if ($element.hasClass('validated')) {
return;
}
// Get all elements in the same group.
var groupName = $element.attr('data-group');
var $groupElements = $('[data-group=' + groupName + ']');
var hasOne = false;
// Check to see if any of the elements in the group is not empty.
$groupElements.each(function() {
if ($(this).val().length > 0) {
hasOne = true;
return false;
}
});
// Add an error to each empty element if the group
// has a non-empty element, otherwise remove the error.
$groupElements.each(function() {
var $groupElement = $(this);
if (hasOne && $groupElement.val().length < 1) {
appendError($groupElement);
} else {
removeCurError($groupElement);
}
$groupElement.addClass('validated');
});
});
}
function appendError($element) {
if ($element.next('span.error').length > 0) {
return;
}
$element.after('<span class="error">*</span>');
}
function removeCurError($element) {
$element.next().remove();
}
$(document).ready(function() {
$('button').on('click', function() {
validateGroups($("[data-group]"));
});
});
You might get some milage out of this solution. Basically, simplify and test your solution on submit click before sending the form (which this doesn't do). In this case, I simply test value of the first checkbox for truth, and then alert or check the required boxes. These can be anything you like. Good luck.
http://jsfiddle.net/YD6nW/1/
<form>
<input type="button" onclick="return checkTest()" value="test"/>
</form>
and with jquery:
checkTest = function(){
var isChecked = $('input')[0].checked;
if(isChecked){
alert('form is ready: input 0 is: '+isChecked);
}else{
$('input')[1].checked = true;
$('input')[2].checked = true;
}
};
//create a bunch of checkboxes
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');

Two fields validation

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" onsubmit="return validate();" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<input type="text" id="course_desc" name="course_desc" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_desc();">
<label id="course_desc_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate_course_desc(){
var TCode = document.getElementById('course_desc').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate(){
return validate_course_name();
return validate_course_desc();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on two field but the problem is if i give first input field valid input and second invalid form get submitted where am i doing it wrong? ...i am very new to this web so any help will be appreciated:)
UPDATED ANSWER:
Fine! Just to be different =)
One line, should validate both fields regardless if the validate_course_name() returns false.
JSFiddle: http://jsfiddle.net/fVqTY/3/
function validate()
{
return (validate_course_name() * validate_course_desc()) == true;
}
Let false = 0, true = 1. Now do the math :)
function validate(){
var value1 = validate_course_name();
var value2 = validate_course_desc();
if(value1 == true && value2 == true)
return true;
else
return false
}
or You can use
function validate(){
var validate = true;
var TCode = document.getElementById('course_name').value;
var TCode1 = document.getElementById('course_desc').value;
if(! /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
if(! /[^a-zA-Z1-9 _-]/.test( TCode1 ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
return validate;
}
and then call this function directly
In this function, You should return only once. So what happens here is that when validate_course_name() gets executed, control is already returned to the calling routine. validate_course_desc() line won't execute.
function validate(){
return validate_course_name();
return validate_course_desc();
}
You should do this:
function validate(){
var bol1 = validate_course_name();
var bol2 = validate_course_desc();
if(bol1 == true && bol2 == true)
return true;
else
return false;
}
Your validate method as given below will return as soon as the first validate method (validate_course_name) is called so it will not execute the validate_course_desc method.
function validate(){
return validate_course_name();
return validate_course_desc();
}
The solution is to execute both the validate method and summarise them to create the return value as given in the above answers
change the function validate()
function validate()
{
if(validate_course_name() && validate_course_desc())
{
return true;
}
return false;
}
Once return statement is executed in a function, other statements that are following return statement does not work.
Therefore every time, validate_course_name() function is called , a bool value is returned and the function validate_course_desc() is not even called/executed.
Therefore, the validate function returns true if validate_course_name() is true and false if validate_course_name() return false.Hence , When you give first field valid input and second invalid, form get submitted.
the validation of both inputfields is the same, so you can make one validation function which takes an element-id as parameter:
function validateInputfield(id){
var TCode = document.getElementById(id).value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById(id).innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
return true;
}
}
Then you can use the function validate() to check if both inputfields are valid:
function validate() {
if (validateInputfield('course_desc_info') == true &&
validateInputfield('course_name_info') == true) {
return true;
} else {
return false;
}
}

input box not working in firefox

I am trying to have a basic filter when someone puts a word into a input box and list items hide on click, this is working fine in chrome but in firefox it is not working at all.
html:
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search" onclick="query_searchvar()"></form>
javascript:
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
if (found == true )
{
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
Any help much appreciated. Thank you.
Hi, I managed to get this working with a combo of all your comments and some jquery resources:
HTML:
<form id="myform" action="#" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search..." />
<input class="my-button" type="submit" value="Search" />
</form>
$('#myform').submit(function() {
var searchquery = String($('#myform input[name=query]').val()).toLowerCase();
if (searchquery == '') {
alert('No Text Entered');
}
var queryarray = searchquery.split(/,|\s+/);
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
var searcharray = searchtags.split(',');
var found = false;
for (var i = 0; i < searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray) > -1) {
found = true;
break;
}
if (found == true) {
$(this).show('normal');
}
else {
$(this).hide('normal');
}
});
return false;
});
document.navsform.query.value ???
onclick="query_searchvar()" ???
event.preventDefault ??? -- lack crossbrowser
Why Use click rather than submit?
missing return false?
why use it?
You're already using jQuery, it would be better to work 100% with Jquery?
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search"></form>
Javascript:
$(document).ready(function(){
$("#navsform").submit(function(event){
event = event||window.event; //Cross
var searchquery=String($("#navsform input[name=query]").val()).toLowerCase();
if(searchquery == ''){
alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function(){
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++){
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
}
if (found == true ){
$(this).show("normal");
} else {
$(this).hide("normal");
}
});
});
return false;//prevents sending the form, remove if necessary.
});
There are a few things, you should change:
Pass in the event object to the handler function.
Attach the eventhandler to the form submit event, not the button. This way the return key will work.
Then you should use a tool like Firebug, Dragonfly or similar. It helps a lot. As mentioned in the comments, you could have found your error.
See Guilherme Nascimento's answer for an example. (But ignore the tone..)

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

Categories

Resources