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 != "";
});
Related
How can I ALERT and PREVENT users from clicking on any elements with the class .popup_element if any VISIBLE INPUTS with class .weight have NO value
Below code is what I tried myself but doesn't seem to work.
$(".popup_element").click(function() {
'' == $(".weight:visible").value &&
alert("Please Select Value First.")
event.preventDefault();
}),
You can do it like this:
$(".popup_element").click(function(event) {
var foundNoValue = false;
$(".weight:visible").each(function(){
if($.trim($(this).val()) == "")
{
foundNoValue = true;
}
});
if(foundNoValue){
alert("Please Select Value First.")
event.preventDefault();
}
})
You can use the .filter() method to test for any blank values:
$(".popup_element").click(function() {
if ($(".weight:visible").filter(function() { return this.value === ""; }).length > 0) {
alert("Please Select Value First.")
event.preventDefault();
}
})
(If you need to treat nothing-but-spaces inputs as blank just use this.value.trim() === "".)
I know I shouldn't really be encouraging your shortcut && instead of if code, but if you want to do that you can have it run multiple statements by using parentheses and the comma operator:
$(".popup_element").click(function() {
$("input").filter(function() { return this.value === ""; }).length && (
alert("Please Select Value First."),
event.preventDefault()
);
});
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
How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}
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.
So I'm trying to style a <textarea> tag to highlight when it has more than one character typed in. (For a contact form). When someone is filling out the form, the fields will all highlight green to let them know its valid. I'm very new to JS and jQuery in general but I'm pretty sure this is supossed to work. I can use the $('#message').addClass('valid') by itself and it will apply the class, but when I add the if/else statement, nothing works. Here is the script
\\ Begin Highlight Code
var $messageval = $('#message').val()
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else ($messageval.length = 0 ){
$('#message').removeClass('valid');
}
});
I've been googling for hours and I can't find anything to dynamically add and remove classes based on a text length variable.
Thanks
You are missing else if
if ($messageval.length != 0 ){
$(this).addClass('valid');
}
else if($messageval.length == 0 ){ //<-- Here
$('#message').removeClass('valid');
}
Basically you can just have
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else { //<-- Here
$('#message').removeClass('valid');
}
I guess this is what you are looking for:-
$(function(){
$('#message').on('keyup', function () {
var $messageval = $.trim($(this).val()); //$.trim here to avoid whitespace preventing validation.
if ($messageval.length != 0) {
$(this).addClass('valid'); //this here represent the textarea dom element, and $(this) is the jquery wrapper.
} else {
$(this).removeClass('valid');
}
});
});
Fiddle
$(document).ready(function(){
$("#message").keyup(function(){
var messageval = $('#message').val();
if (messageval.length > 1) {
$('#message').addClass('valid');
} else {
$('#message').removeClass('valid');
}
});
});
change your code to this
$(document).ready(function(){
$('#message').trigger('change');//if you initially want to check the textarea
$('#message').on('change', function(){
var $messageval = $(this).val();
if ($messageval.length != 0 ){
if (!$(this).hasClass("valid")) {
$(this).addClass("valid");
}
}
else ($messageval.length == 0 ){
if ($(this).hasClass("valid")) {
$(this).removeClass("valid");
}
}
});
});
Cheers!