Check if placeholder text already exists within a string - javascript

I have an #error paragraph. Everytime there is an error within the form on submit. The inputs placeholder text gets added to the #error paragraph.
My problem:
It happens everytime a user clicks submit. So the #error message returns:
Please fill in yourfirst name, last name, company, position, first
name, last name, company, position, first name, last name, company,
position, first name, last name, company, position, first name, last
name, company, position, first name, last name, company, position,
I've looked for other solutions and tried this:
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
Is there any way to check if the placeholder text already exists in the #error message? Here's a fiddle. I'm sorry it's so convoluted. But its what i've been working on and had it handy.
Thanks for your help in advance!

http://jsfiddle.net/8YgNT/20/
var errorText = '';
//Validate required fields
for (i = 0; i < required.length; i++) {
var input = $('#' + required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
if (input.attr('placeholder').indexOf($('#error')) >= 0) {
// do nothing
} else {
errorText = errorText + $(input).attr('placeholder').toLowerCase() + ', ';
}
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
$('#error').html('').append('Please fill in your ' + errorText);

I simple add one line in your fiddle and it's working now:
required = ["id_first_name", "id_last_name", "id_firmbox", "id_job_title"];
errornotice = $("#error");
emptyerror = "Please fill out this field.";
$("#startform").submit(function(){
//Validate required fields
$("#error").html("Please fill in your");
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
// =====Here===== //
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
// ============== //
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
if ($(":input").hasClass("tobefixed")) {
return false;
} else {
errornotice.hide();
return true;
}
});
$(":input").focus(function(){
if ($(this).hasClass("tobefixed") ) {
$(this).val("");
$(this).removeClass("tobefixed");
}
});
This line do the all trick:
$("#error").html("Please fill in your");
Saludos ;)

If you want to check whether #error contains the string you're wondering about, you can use
($('#error').text().indexOf(a_string)) != -1
This will return true if #error contains a_string.
There's a longer discussion on searching strings for other strings in this question.

It seems you're doing it the wrong way round (and forgetting to get the text out of the #error element):
if ( $('#error').text().indexOf( input.attr('placeholder') ) >= 0)

Related

Comparing two text box which contains email_Id

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]);
}
}

how to add one error instead of multiple errors

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
}

Remaking jQuery form validation

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");
}
});
});

jquery custom validation script without plugin?

i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});​
DEMO

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories