Javascript Form Validate - javascript

I am trying to validate input on an HTML form. I am trying to use one script to validate various forms that have several similar elements. All in all there are about 15 different fields but I am only putting 3. Below works on the form that has all of the elements but fails on any form that does not have a specific field.
if (form.name.value == ""){ // Check if blank
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else if ( !/^\w{10}$/.test( form.phone.value )) { // Check for phone
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; // Submit!
Since this only works if all are present what i want to do is validate only if it exists. I have tried nesting the validation under a statement that should check for the element before trying to validate it and if the element doesn't exist it should move on to the next.
if (document.forms[0].name){ //does field exist?
if (form.name.value === ""){
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else if (document.forms[0].phone){
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else{
return true; // Submit!
}
Any help help would be appreciated!

At present you are checking that (document.forms[0].name) is available and then if this is dead it check if (document.forms[0].phone) is true and then...... and then if none are true it resorts to the 'else' and returns are true. The use of if else means that you only bother with anything after if this part has failed.
You could try.
if (document.forms[0].name) {
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
}
if (document.forms[0].blah) {
do stuff...
if fail
return false;
}
return true;
As the function is going to return as true anyway, you don't need to state return true anywhere else (also this will stop the process as it has returned and stopped). The only reason to stop the process if things have gone wrong.. hence return false;

If you just need to validate a form, you don't need to write javascript nowadays. You can use html5 forms. Even if you have to support browser without this feature, you can put the webshims lib at your page to enable it.

Related

document on submit isn't submitting form

I have a button outside of the form that when pressed, submits my form. That form has an event on it for onSubmit that fires off and then just does some form checks, making sure fields are present. At the end of the form, I return true and nothing happens. Can't seem to figure this out. Appreciate the extra set of eyes. I did verify that that function is being called and makes it all the way past the checks, just nothing happens. Here's the code:
$(document).on('click','.but_addTask',function(e){
e.preventDefault();
$('#addTaskForm').submit();
});
$(document).on('submit','#addTaskForm',function(e){
e.preventDefault();
var description = $('#description').val();
var dueDate = $('#dueDate').val();
if(!$('.taskClientID').length){
alert('Please add client(s) to task');
$('#taskClientSearch').focus();
return false;
}
if(description==""){
alert("Please enter a description")
$('#description').focus();
return false;
}
if(!$('.taskAuditorID').length){
alert('Please add owner(s) to task');
$('#taskOwnersSearch').focus();
return false;
}
if(dueDate==""){
alert("Please enter a dueDate")
$('#dueDate').focus();
return false;
}
console.log('made it!');
return true;
});
You already called e.preventDefault(); at the start of the callback, which suppresses the default behaviour of the event (in this case of course, that behaviour is to submit). By the time you return true it's too late.
If you remove that line, you should be ok.
Docs: https://api.jquery.com/event.preventdefault/

jQuery Function and Javascript Functions Not Working Together

I am trying to run a jQuery function with some other Javascript functions. I suppose I am not understanding the syntax correctly. I have a colorbox that opens on page load with a form in it. When the form is submitted I am trying to have a validation run first and then if successful run a jQuery function that closes the Colorbox and validates the parent window. This is where I'm at now (by the way, I've been all around the circle with this. I've been able to get the jQuery function to work, I've gotten the validation functions to work but I've never gotten them to work together. I apologize if I've gotten way off base but I think I've drifted away since I was trying some new things):
Just tried this:
window.echeck(str) = function {
var at="#"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}
return true
}
window.ValidateForm() = function{
var emailID=document.MailingList.emailaddress
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
$(document).ready(function() {
$('#submitbutton').live('click', function(e) {
ValidateForm();
parent.$.fn.colorbox.close();
parent.location.href = "/SearchResults.asp?Cat=1854";
});
});
I didn't execute any of the functions.
When I remove ValidateForm(); from the jQuery and when I put the syntax of the javascript functions back to function ValidateForm(); instead of window.ValidateForm = function() the jQuery works but of course the other javascript functions do not.
an I not create nested functions inside of the main jQuery function
You can't reference functions from outside the $(document).ready(function() { }); block, because it's a private scope. You need to either define one of the functions outside of the scope, so that it's accessible --
$(document).ready(function() {
// define in the global scope (window) so that it's accessible anywhere
window.ValidateForm = function() { ... }
});
// this works
ValidateForm();
or wire up your events by using on --
$(document).ready(function() {
$("#theform").on("submit", ValidateForm);
});

Javascript / jQuery return false does not stop execution

I have a code block that checks certain elements before allowing a form to submit, the loop loops through OK.
I would anticipate, or at least had hoped that the first time it finds a problem, an alert is shown and then execution stops. What is actually happening is that alerts show multiple times, right down to the last one, and only the last one actually returns false!
I don't understand why this is, what am I doing wrong? The JavaScript is below.
$('#deliverInForm').submit(function(){
$('.childRow').each(function(){
if($(this).find('.thisBinName').val()!='' || $(this).find('.unitQty').val()!=''){
if($(this).find('.thisBinName').val()==''){
alert('You have entered a quantity but no Bin, please correct and try again!');
return false;
}else if($(this).find('.unitQty').val()==''){
alert('You have entered a Bin but no quantity, please correct and try again!');
return false;
}else if($(this).find('.unitQty').val()==0){
alert('Can\'t move zero units into a bay, please correct and try again!');
return false;
}else if($(this).find('.unitQty').val()<0){
alert('Can\'t deliver in minus units into a bay, please correct and try again!');
return false;
}
}
});
if($('#supDocNo').val()==''){
alert('Can\'t leave Supplier Reference blank, please correct and try again!');
return false;
}
return true;
});
make your function take an event argument, then call event.preventDefault()
e.g.
$('#deliverInForm').submit(function(event){
$('.childRow').each(function(){
if($(this).find('.thisBinName').val()!='' || $(this).find('.unitQty').val()!=''){
if($(this).find('.thisBinName').val()==''){
alert('You have entered a quantity but no Bin, please correct and try again!');
event.preventDefault();
return false;
}else if($(this).find('.unitQty').val()==''){
alert('You have entered a Bin but no quantity, please correct and try again!');
event.preventDefault();
return false;
}else if($(this).find('.unitQty').val()==0){
alert('Can\'t move zero units into a bay, please correct and try again!');
event.preventDefault();
return false;
}else if($(this).find('.unitQty').val()<0){
alert('Can\'t deliver in minus units into a bay, please correct and try again!');
event.preventDefault();
return false;
}
}
});
if($('#supDocNo').val()==''){
alert('Can\'t leave Supplier Reference blank, please correct and try again!');
event.preventDefault();
return false;
}
return true;
});
The problem is that inside your each loop, the return false just exits the function you have passed to each. According to the docs, this will exit the each loop, but it wont exit your submit handler.
You could do something ugly like this:
$('#deliverInForm').submit(function(){
var exit = false;
$('.childRow').each(function(){
if($(this).find('.thisBinName').val()!='' || $(this).find('.unitQty').val()!=''){
if($(this).find('.thisBinName').val()==''){
alert('You have entered a quantity but no Bin, please correct and try again!');
exit = true; // <----------------set flag
return false;
//...
});
if(exit) return false;
// ...
});
from jquery each documentation
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I think you must move your return false to the each loop and not inside the find()
Try this:
$('#deliverInForm').submit(function(){
var errLog = '';
$('.childRow').each(function(){
if($(this).find('.thisBinName').val()!='' || $(this).find('.unitQty').val()!=''){
if($(this).find('.thisBinName').val()==''){
errLog += 'You have entered a quantity but no Bin, please correct and try again!\n';
}
if($(this).find('.unitQty').val()==''){
errLog += 'You have entered a Bin but no quantity, please correct and try again!\n';
}
if($(this).find('.unitQty').val()==0){
errLog += 'Can\'t move zero units into a bay, please correct and try again!';
}
if($(this).find('.unitQty').val()<0){
errLog += 'Can\'t deliver in minus units into a bay, please correct and try again!';
}
}
});
if($('#supDocNo').val()==''){
errLog += 'Can\'t leave Supplier Reference blank, please correct and try again!\n';
}
if( errLog != '' ) {
alert( errLog );
errLog = '';
return false;
}
return true;
});
Hope it helps.
the event handler function needs to return the value.
$(".link").submit(function(){
return false;
});
To show the first error dialog and return false you have to do something like this...
$(".link").submit(function(){
var submit=true;
$("div").each(function(){
if(submit) // comment this out to show all dialogs
if(!condition){
submit = false;
alert("problem");
return ""; // return here is irrelevant
}
})
return submit;
});
One more thing, if your function throws an error it will not return false and the submit will occur anyway...
$(".link").submit(function(){
throw new Error("foo");
return false; // never happens form submits as if returning true;
});

Javascript: how to bring focus to an element, and show a warning message

Preface, I really don't know javascript at all.
I am trying to validate the email address of a form. If validation fails, I would like to focus on the invalid email field, and show a warning message. The below code properly returns true or false if the "focusElement" line is removed. However, it always returns true with that line included (presumably because the line is invalid and the code does not execute. Is there a proper/simple way of focusing on this element and showing the message?
function validateForm(formElement)
{
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailPattern.test(formElement.tfEmail.value))
{
return true;
}
else
{
focusElement(formElement.tfEmail,'Please enter a valid e-mail address.');
return false;
}
}
Use .focus() and alert()
...
else
{
alert('Please enter a valid e-mail address.');
formElement.tfEmail.focus();
return false;
}
If you would like the functionality to be in a separate function like your example:
...
else
{
focusElement(formElement.tfEmail, 'Please enter a valid e-mail address.');
return false;
}
function focusElement(obj, msg)
{
alert(msg);
obj.focus();
}
function focusElement(el, message) {
alert(message);
el.focus();
}
Try:
alert("Ur err msg");
document.getElementById("yourEmailFieldId").focus();
You should try use jQuery and jQuery Validate for this task.
jQuery is the most used JavaScript framework, it can simplify a lot of any tasks in JavaScript.
jQuery Validate is a very used plugin for validation, based on jQuery.

jquery - validation plugin

I make a simple validation plugin, that return false if input fail validation, the problem is this plugin only works with one input at a time. I want it to work with all input at the same time.
the code
$.fn.validate = function(options){
var defaults = {
required:true,
minChar:0,
maxChar:0
},
o = $.extend({},defaults, options);
this.each(function(){
var $this=$(this);
var val = $this.val();
if(o.required==true && val==''){
return false;
}else if(o.minChar>0 && val.length < o.minChar ){
return false;
}else if(o.maxChar>0 && val.length >o.maxChar ){
return false;
}
else{return true;}
});
}
call
if(!$('#name').validate()){
$('.name_inline_error').text('require name');
return false;// return false to stop ajax form submiting
}
if(!$('#email').validate()){
$('.email_inline_error').text('require email');
return false;// return false to stop ajax form submiting
}
What the code will do is, if two inputs are empty, the plugin will only tell the name input error, only when the name input was validated, the form will tell the email input error. While, I want to see two errors at the same time.
When you return, you are skipping the rest of your function. Try something like this:
valid = true;
if(!$('#name').validate()){
$('.name_inline_error').text('require name');
valid = false;
}
if(!$('#email').validate()){
$('.email_inline_error').text('require email');
valid = false;
}
return valid;
(+1 to Matt Ball's comment, however -- rolling your own on this one is going to take a long time.)

Categories