Conflicting Javascript preventing form validation - javascript

im trying to validate a form before its submitted to the database but something seems to be conflicting with it and its just sending anyway without any values
heres my form:
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<span style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px;">Ally McCoist will be sacked on</span>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/submit-button-small.png" name="submit" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres my validate javascript:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(e){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
i also have this javascript on the page fore my jquery UI datepicker which i think might be causing the problem
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
fingers crossed one of you can see something that might fix this problem

It is possible that the form was filled out by a person with JavaScript disabled or that a person or machine simply invoked an HTTP POST, with whatever values they saw fit. For this reason, it is necessary to perform validation on the server-side (i.e. in send.php), not just on the client-side (in the JavaScript file). JavaScript validation is really just a UI optimization that allows a user to be immediately told that something is wrong without requiring a round-trip communication to the server. From a user-interface perspective, JavaScript validation is important, but from a security perspective it is useless.

Related

How to know required field validation triggered or not? [duplicate]

This question already has answers here:
JavaScript validation for empty input field
(15 answers)
Closed 3 years ago.
I have a big form with lot of fields and most of them are required fields. so i wanted to show pop-up alert message saying please fill required field.
<input name="fname" id="fname" type="text" class="form-control" required>
also i m showing usual message below that particular field,
i need something like on submit click
If (some fields required field error got triggered )
{
show alert pop-up message ;
}
I am new to this thing so..
function checkEmpty()
{
var fname = document.getElementById('fname').value;
if(!fname)
{
alert('Field is empty')
}
}
<form onsubmit='checkEmpty'>
<!--Form contents-->
</form>
Validation with javscript can easily be bypassed since it happens in the client side.
Try this
<form onsubmit="myFunction()">
<input name="fname" id="fname" type="text" class="form-control" required>
<form>
Use the following Function to check fields
function myFunction() {
var fname=document.getElementById('fname').value;
if(!fname)
{
alert("please fill required field");
}
}
You can check multiple fields in if conditions by putting || Sign. eg you have 2 filed fname and lname. You can check by if(!fname || !name)
You need to show overall alert as well as individual error message below each required field.
To do so using jQuery,
<form>
<input name="fname" id="fname" type="text" class="form-control validateclass" required>
<span class="spnError"></span>
<input name="lname" id="lname" type="text" class="form-control validateclass" required>
<span class="spnError"></span>
<input id="btnClick" type="button" value="Submit Form"/>
</form>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function()
{
$(".validateclass").each(function() {
var fieldValue =$(this).val();
if(fieldValue == null || fieldValue == "")
{
$(this).next().css( "color", "red" ).text("Field is required");
}
else
{
$(this).next().text("");
}
});
});
});
</script>

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

How to check if textbox is empty and display a popup message if it is using jquery?

I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />

jQuery validation not working for input fields

I have jQuery validation for my input fields. But seems like not working :(
$('form')
.submit(function() {
var name = $.trim($('#TxtName').val());
var dob = $.trim($('#TxtDesig').val());
var salary = $.trim($('#TxtSalary').val());
if (name === "" || dob === "" || salary ==="") {
alert("All fields are mandatory");
}
return false;
});
Here is my html form:
<form class="form-group" method="post">
<label class="control-label">Employee Name:</label>
<input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" /><br />
<label class="control-label">Designation:</label>
<input class="form-control" type="text" id="TxtDesig" name="Designation" value="" /><br />
<label class="control-label">Salary:</label>
<input class="form-control" type="date" id="TxtSalary" name="Salary" value=""/><br/>
Here is how to code your jQuery validation.
I need to show it in a fiddle since the stacksnippet does not allow form submit
https://jsfiddle.net/mplungjan/n6mcyf6x/
$(function() {
$('form').on("submit", function(e) {
var name = $.trim($('#TxtName').val());
var dob = $.trim($('#TxtDesig').val());
var salary = $.trim($('#TxtSalary').val());
if (name === "" || dob === "" || salary === "") {
alert("All fields are mandatory");
e.preventDefault();
}
});
});
As mentioned by Rhys Bradbury an alternative is to add "required" to each field .
It may however not be supported by older browsers (like IE<10) for example)
http://caniuse.com/#feat=form-validation
Why do this in jQuery? Why not use HTML required attribute on form inputs?
ref:
http://www.w3schools.com/jsref/prop_text_required.asp
example:
<input placeholder="required a value here please" required/>
FYI this is HTML5
You can validate by two process.
process 1: Add following attribute into validated controls as one I edited from your source. Easiest way rest will be responsible of jQuery validation engine.
<input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" required='' data-msg-required='Please provide name.'/>
Process 2: If you want your controlled validation then you need write piece of code as follows.
$("#form").validate({
rules:{ //Validation rules work on name attribute
EmployeeName:{ //Condition Area
required:true
}
},
messages:{ //user information area
EmployeeName:
{
required:"Please provide Employee Name" /// Message to user for required fields
}
}
});
You get more information from jQuery Website

How to validate for either form fields with vanilla JavaScript

I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form" action="" method="POST">
<input type=hidden name="" value="">
<input type=hidden name="" value="">
<p class="errmsg" id="name_errormsg"></p>
<input id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
<input id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
<input id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />
<textarea id="description" name="description" placeholder="How can we help you?"></textarea>
<input type="submit" name="submit" value="Send message">
</form>
$(document).ready(function() {
$overlay = $(".modal-overlay");
$modal = $(".modal-frame");
$modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
if($modal.hasClass('state-leave')) {
$modal.removeClass('state-leave');
}
});
$('.form-close-button').on('click', function(){
$overlay.removeClass('state-show');
$modal.removeClass('state-appear').addClass('state-leave');
});
$('#contactformbtn').on('click', function(){
$overlay.addClass('state-show');
$modal.removeClass('state-leave').addClass('state-appear');
});
var formHandle = document.forms[0];
formHandle.onsubmit = processForm;
function processForm(){
var emailInput = document.getElementById('email');
var emailValue = emailInput.value;
var phoneInput = document.getElementById('phone');
var phoneValue = phoneInput.value;
var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
var regexEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
nameErr = document.getElementById("name_errormsg");
nameErr.innerHTML = "Please enter your phone number or a valid email address.";
nameErr.style.color = "red";
return false;
}
}
});
If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
....
Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?

Categories