OK, i have a couple of inputs. I have this code to validate them.
$("#form1").submit(function(){
var isFormValid = true;
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your First Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your Last Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Select Your Volunteer Choice");
return isFormValid;
});
For some reason, i get a message after a message. What i was aiming for is that it only show me the next field that has not been field out, not all of them at the same time. If you have a question, please comment, it is hard to explain....do not down vote until you give me a chance to better explain.
Here is how to simplify your code, and make it work like intended.
First, since you use the same method to validate all the fields, wrap that in a function instead of repeating the code:
function isFieldEmpty(jQuerySelector) {
return $.trim($(jQuerySelector).val()).length == 0
}
Second, use a single submit handler to check everything, and return false if any field does not pass validation:
$("#form1").submit(function(){
if(isFieldEmpty('#first_name')) {
alert("Please Enter Your First Name");
return false;
}
if(isFieldEmpty('#last_name')) {
alert("Please Enter Your Last Name");
return false;
}
if(isFieldEmpty('#dropdown')) {
alert("Please Select Your Volunteer Choice");
return false;
}
// Will return true only if all fields passed
return true;
});
I'm not familiar with JQuery but I think what is happening is your are binding 3 functions to your form, which means they all get called
when you want to do is create 1 function validate that calls your sub validations functions.
also I would recommend you change your sub validation methods to return the message instead of a boolean, this way you can display all the errors in 1 alert.
You have multiple alerts because you bind different functions to the submit event of the form: each one checks a different field and fires an alert if the field is empty.
You need to move the three validation steps in only one function and bind that function to the submit event.
Something like:
$("#form1").submit(check);
function check() {
var isFormValid = true;
var errors = array();
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your First Name");
}
});
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your Last Name");
}
});
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Select Your Volunteer Choice");
}
});
if (!isFormValid) {
var errorMsg = "";
for (var i = 0; i < errors.length; i++) {
errorMsg += errors[i] + "\n";
}
alert(errorMsg);
}
}
This is because of the redundancy on your code, same function, same identifier, same logic, same event handler, useless each with an id selector.
The only thing different are the subjects. Here is my suggestion.
$("#form1").submit(function(){
var errors = [];
if($("#first_name").val().length == 0){
errors.push("Please Enter Your First Name");
}
if($("#last_name").val().length == 0){
errors.push("Please Enter Your Last Name");
}
// and so on
if(var isFormValid = errors.length > 0) {
alert('you have errors');
//errors contains all the error message if you need them
}
return isFormValid;
});
Related
window.onload=alert("please,Sign Up first");
window.onload=pageload;
function pageload() {
var signup=document.getElementById("signup");
signup.onsubmit=signupp;
}
function signupp(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if (st=="First name" || st=="") {
alert("please enter your first name");
return false;
}
else if (ls=="Last name" || ls=="") {
alert("please enter your last name");
return false;
}
// what should i type here to move to loginn function ?
}
function loginn(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if(username==""){
alert("please enter your username or your phone number");
return false;
}
if(password==""){
alert("please enter your password");
return false;
}
}
You can set the login wrapper div via CSS to:
#loginform{display:none;}
And then after registration set via JS to:
var loginform=document.getElementById("loginform");
loginform.style.display = 'block';
Can someone help me out with validation of two text-box with same email Id.
I was able to pop an alert if both the text-box contain the same email Id via JavaScript(my requirement was both text-box cant have same email) but now I m facing a problem if second text box contain more then one email_Id separated my comma(,) the validation doesn't work.
I don't want email that is present in first text box repeat into second text-box.
My code:
<script language="javascript" type="text/javascript">
function validated() {
if (document.getElementById("<%=txtCountry.ClientID %>").value = document.getElementById("<%=txtnewViewer.ClientID %>").value) {
alert("Presenter cant be attende");
return false;
}Else{
return true;
}
}
</script>
check this code out
<script language="javascript" type="text/javascript">
function validated()
{
if (document.getElementById("<%=textbox1.id %>").value == document.getElementById("<%=textbox2.id %>").value)
{
alert("text-box cant have same email");
return false;
}
else
{
alert("Valid");
return true;
}
}
</script>
Can you try this.
var f_email = document.getElementById("f_email").value;
var s_email= document.getElementById("s_email").value;
if(f_email === s_email) {
// do something when email ids are same.
alert("email ids are same");
}
else {
// do something when email ids are same.
alert("email ids are not same");
}
First, you if statement contains an = who always return true and modify your variable (in place of ==).
function validated() {
var clientId = document.getElementById("<%=txtCountry.ClientID %>").value,
viewerId = document.getElementById("<%=txtnewViewer.ClientID %>").value;
if (clientId == viewerId) {
alert("Presenter cant be attende");
return false;
}
return true;
}
After that you can use : Array.indexOf():
var clients = clientId.split(","), viewers = viewerId.split(",");
// Here we have two arrays with all datas
for(var i = 0; i < clients.length; i++){
var k = viewers.indexOf(clients[i]);
if(k !== -1) {
alert(clients[i], "=", viewers[k]);
}
}
Hi I have designed my form now i am unsure how to combine all the alert messages instead of them popping up one at a time , please could someone tell my how to do this in simple terms as i am new to javascript. thankyou in advance. below is my script.
function validateForm() {
// this part of the script will collate all errors into one should the user leave an input blank
var Fname=document.forms["myForm"]["fname"].value;
var Lname=document.forms["myForm"]["lname"].value;
var address=document.forms["myForm"]["addr1"].value;
var postcode=document.forms["myForm"]["pcode"].value;
var email=document.forms["myForm"]["email"].value;
var number=document.forms["myForm"]["tel"].value;
var date=document.forms["myForm"]["mydate"].value;
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date)
{
alert("Please make sure all fields are filled or checked correctly out ");
return false;
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode))
{
alert("That Post Code is incorrect, correct way mk4 4tr");
return false;
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail))
{
alert("That email is incorrect");
return false;
}
// end of email script
// start of phone number script
var phonestring = /^(?:0|\+44)[12378]\d{8,9}$/;
if (!number.match(phonestring))
{
alert(" incorrect,correct format 01908234874");
return false;
}
// end of phone script
//start of gender script
if ( ( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
// end of gender script
//start of age group script
if((myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )){
alert("please select an age group");
return false;
}
// end of age script
//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;
if (!date.match(dateformat))
{
alert("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
return false;
}
var today = new Date();
var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits
var courseDay = date.substr(0,2)//e the first and second digits
var dateToCompare = new Date(courseYear, courseMonth, courseDay);
if (dateToCompare < today) {
alert("this date is in the past");
return false; }
//end of date field
else
{ alert(" Thank you a member of our team will get back to you shortly");
return true;}
}
create some kind of collection that you can append to and instead of alerting independantly, just add them to the set. Something like:
function validateForm(){
var errors = []; // new array to hold all the errors
/*
validation code that instead of
alert('error')
use
errors.push('error');
Also remove any premature `return` statements and
leave them until the end.
*/
// next check if there are errors
if (errors.length > 0){
// display them
alert('Following errors found:\n- ' + errors.join('\n- '));
// also return false to flag there was a problem
return false;
}
// if we reached this code there were no errors
return true;
}
Add all your errors to an array and then alert them at the end, if any exist:
function validateForm() {
var errors = []; //array for holding errors
.
.
.
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date) {
errors.push("Please make sure all fields are filled or checked correctly out "); //add error
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode)) {
errors.push("That Post Code is incorrect, correct way mk4 4tr"); //add error
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail)) {
errors.push("That email is incorrect"); //add error
}
if(errors.length > 0) {
alert('The following errors occurred: ' + errors.join('\n')); //alert errors if they exist
return false;
}
return true; // allow submit
}
I have three fields ForteID, disposition and Cancel_Disposition. Right now I have this code in my javascript and it works:
function validateForteID(){
if(document.csform.ForteID.selectedIndex==0)
{
alert("Please select your Forte ID.");
document.csform.ForteID.focus();
return false;
}
if(document.csform.disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.disposition.focus();
return false;
}
if(document.csform.Cancel_Disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}
return true;
}
What I am looking to do and not exactly sure how to do it, but if the field Disposition is either LOC or Backout, I then want it to do this part of the code:
if(document.csform.Cancel_Disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}
But only if the disposition is LOC or Backout. Let me know if there I need more explanation, thank in advance!
var cancel_disposition_value = document.csform.Cancel_Disposition[document.csform.Cancel_Disposition.selectedIndex].value;
if(cancel_disposition_value=='LOC' || cancel_disposition_value=='Backout')
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}
I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// 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(){
//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")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// 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(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
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")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});