Jquery focusout runs several time by each mouse out click - javascript

I try to validate the textbox by mouse out in jquery, my code is running by any mouse out means it shows Enter valid Email. several times, any time that I click outside the textbox.
This is my code:
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
my code is not working when it is outside the document.ready.
This is what I get when I run by each time I click:

$(this).after('<div class="Required">Enter valid Email.</div>');
this will add a new after every focus out of the input box.
Instead have a placeholder div below the text box.
<div id="emailErrorMsg"></div>
and do
$('#emailErrorMsg').html('Enter valid Email.');
this will also let you add more error messages.

Remove the div before you add one to prevent repeats.
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
if($(this).next().hasClass('Required'))
$(this).next().remove();
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});

I have implemented some code to validate text box and insert error div after the element if entered value is not valid.
I hope below code will solve your problem
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
var errorLabel = errorsFor(this);
$(this).addClass('ChangetoYellow');
if(errorLabel.length > 0){
$(errorLabel).show();
}
else {
$(this).after('<div for='+ this.name +' class="required">Enter valid Email.</div>');
}
return false;
} else {
$(this).next(".required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
function errorsFor( element ) {
var name = idOrName(element);
return $('.required').filter(function() {
return $(this).attr("for") === name;
});
};
function idOrName( element ) {
return element.name ? element.name : element.id || element.name;
};
});
Test sample code

Try This one first remove previous error messages and add it.
JS
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).parent().find(".Required").remove();
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).parent().find(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
For Simple Example Fiddle (if u want add the regular expression and test it) -
http://jsbin.com/pujemay/edit?html,js,output

Related

How come multiple classes not targeting in textarea?

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});

Jquery validation code for not allowed only blank space in textbox

i m looking for code in which for not allowed only blank space... for e.g i have one textbox and i have tried this
$(document).ready(function()
{
$("#mybutton").live('click',function()
{
var txt_family_name=$("#mytextbox").val();
if(txt_family_name =="" || txt_family_name ==null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
this above code i have tried and its not working. so pls help me on that.. on one of my button i m calling this above code
Example : space....with any text -- output should be not null
: space space.... any space without any other text -- output should be null
you can use the length attribute and the trim method to remove the trailing spaces, if any:
$("#mybutton").on('click',function()
{
var length = $.trim($("#mytextbox").val()).length;
if(length == 0)
{
alert("null");
}
else
{
alert("not null");
}
});
See the updated code it's working
$(document).ready(function()
{
$("#clickme").on('click',function()
{
var txt_family_name=$.trim($("#mytextbox").val());
if(txt_family_name ==="" || txt_family_name ===null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
Jquery Validation : require method only check the length of the input. So it allow the blank space.The solution will be the simple change the one line code in it.
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
}
in above code change value.length to $.trim(value).length
so simply remove the blank space
you can use regexp.
$(document).ready(function() {
$("#mybutton").bind('click', function() {
var txt_family_name = $("#mytextbox").val();
if (txt_family_name.replace(/\s/g, '') == "") {
alert("null");
} else {
alert("not null");
}
});
});
//To add method to remove blankspaces
$.validator.addMethod("blankSpace", function(value) {
return value.indexOf(" ") < 0 && value != "";
});

jquery form validation without click -> when ok show div

is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/

Delete tagLabel in input-Field with tagit

I use https://github.com/aehlke/tag-it this Addon for Autocomplete Tagging
The user just can take labels out of the existing array sampleTags
Before the tag is added I check whether the element is in Array or not
beforeTagAdded: function(evt, ui) {
var counter = jQuery.inArray(ui.tagLabel, sampleTags);
if (counter != -1 ) { return true; }
else { alert('This word is not in array'); return false; }
},
But the input then is not deleted .
How can I do this?
jsFiddle: http://jsfiddle.net/zqDXL/3/
Try this:
if (counter != -1) {
return true;
} else {
alert('This word is not in array');
$('.tagit-new input').val('');
return false;
}
Demo here

How do I fix two bugs for my jQuery form Validation code?

My code basically adds a class error if field is invalid and if the field is valid, the error class is removed and form is submitted normally.
I am having trouble figuring out two small bugs for the form validation code I created.
Bugs listed below:
1) If you enter the correct content within one field, and click submit, the length of the error class does not update on first submit click. It takes two submit clicks for the length to update. (view console.log)
2) If you change the content of the input field and click submit (all works well, error class is removed) BUT if you decide to delete your updated text & leave the field blank, the error class does not get re-applied.
Would be great if I can get some assistance solving this.
Please let me know if anything is unclear.
Thanks in advance:
JSFIDDLE
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
Like dc5 said for #2 don't remove the req class.
And for #1 - You're looking for errors (.req) before it is removed.
See this working fiddle. It is an example how your code work but maybe you can find a cleaner solution.
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'), errorCheck = 0,
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error');
}
});
errorCheck = $(this).find('.error');
console.log(errorCheck.length);
if ( errorCheck.length === 0 ) {
return true;
} else {
return false;
}
});
for #2, You are moving the 'req' class as well as the 'error' class when clearing the error. The next time through the call, the input is no longer found through your selector $(this).find('.req')
For #1 - I don't understand the problem as you have described it.
I made it easier for you, actually your code is a mess,
here is a fiddle:
Jsfiddle validate Demo
CODE:
$('#submit_form').click(function() {
var flag = 0;
var count = 0,
total = $(".req").length;
var validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$('.req').each(function(){
count++;
if($(this).attr('id')=='email') {
if(!validateEmail($(this).val())){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='name') {
if($(this).val().length < 3){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='com') {
if($(this).val().length < 3&&$(this).val()!=''){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if ( total==count&&flag<1) { alert('submit'); }
});
});
Validation rules:
name - must be bigger then 2.
email - true on pattern match function.
comment - if typed, must be bigger the 2 chars (just to understand how can it be done).
If this example is not clear or you need more help don't hesitate... I'm bored.

Categories

Resources