Check if string is empty with jquery - javascript

I am running a client side validation javascript which will submit a form via an ajax post after validating the data. Here is the javascript:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $("#comments").val();
if ((!comment) || (comment > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
The four input fields are three text inputs for name, email and phone and then one textarea for the comments/queries section. The problem is that if I leave the textarea blank or enter over 100 characters the script does not go into the if ((!comment) || (comment > 100))
statement. I am wondering if there is a different value that gets assigned to a textarea when it is blank that is stopping the code from seeing it as empty ?

You need to check the length property of comment (also, you have a few extra parens. They won't break anything, but aren't needed).
if (!comment || comment.length > 100) {
What's currently happening is that you're trying to determine if a given string is less than a number, which is quite silly, so JS declares it false. Checking comment.length compares it to a number, which is what you wanted it to do.
!comment works because an empty string is falsy, though what you think is empty might not be (for instance, a string with a space is non-empty: ' '). Use .trim() to eliminate that pesky whitespace:
if (!comment.trim() && comment.length > 100)
(as a side note, none of the above requires jQuery, it's all JavaScript)

You have two symptoms:
Leaving the field blank doesn't trigger the condition, and
Entering more than 100 characters doesn't trigger the condition.
The others have pointed out why #2 doesn't happen: You're doing comment > 100 where you need comment.length > 100.
The first is most likely because the field isn't completely blank, but rather has some whitespace in it. We can remove that whitespace with jQuery's $.trim (which works cross-browser, whereas .trim on strings doesn't work in IE8). So:
var comment = $.trim($("#comments").val()); // trim removes leading and trailing whitespace
if ((!comment) || (comment.length > 100)) { // Include .length
That's assuming you don't want to count leading and trailing whitespace.

if ( comment == '' || comment.length > 100 ) {

one reason that everyone here are making a mistake, if i provide an empty string which contains 100 empty spaces they return true.
the current and right way to check for empty string is
if (!comment && comment.trim().length > 100)
trim actually mean that empty spaces from the begining and end of the string are deleted.

Related

Javascript validate password field input

i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]

Verifying text-field entry and changing class for user feedback

In this jsfiddle example, I have created a text-entry field that responds to the characters entered and appends a class to the parent <div> element for visual feedback based on whether the entry is expected, partial, or has an error.
In this case, the text field is for serial number entry; the field contents will eventually be sent to a dynamic table for building out an order. Because of this, the serial number must have an absolute value in the prefix (i.e: ABCDE in the example) and contain exactly 14 characters... I'm having difficulty coming up with a working code that will turn the text box green if the prefix is correct and remain green regardless of the remaining 9 characters (although they do need to be strictly numeric and end in a letter).
Additionally, I have a feeling there is a shorter and more elegant way to implement the script for the prefix check. Currently, I'm using:
if (el.value == "abcde" || el.value == "ABCDE") {
document.getElementById('serial').className = 'serial-entry success';
} else if (el.value == "a" || el.value == "ab" || el.value == "abc" || el.value == "abcd" || el.value == "A" || el.value == "AB" || el.value == "ABC" || el.value == "ABCD") {
document.getElementById('serial').className = 'serial-entry warning';
... where I know there's got to be a better way to write the expected ascending prefix values other than (el.value == "a" || el.value == "ab" ||... and so on. Using my current method, I would need to write half-a-billion variants of the el.value in order to satisfy all combinations.
Please be aware that I am not versed in JS; everything I know I've picked up from this site. It's the equivalent of moving to a foreign country and learning the language solely by eavesdropping on conversation - my grammar, syntax, and vocabulary are sparse, at best. In other words: feel free to humiliate me with sage-like wisdom.
--- EDIT: Answered! ---
Thanks to Felix Kling for the solution. I should have been more clear on where the state changes would occur, so I'll do so now and then include the code.
Rules:
1.) As the user enters the first letters of the prefix in correct order ("abcde"), the class of the text box should change to let the user know that they're on the right track, but not quite finished (partial).
2.) If the prefix is entered exact and we're agnostic of the following numbers ("123456789"), but they eventually do enter the correct prefix and a total of 14 characters, then the state (class) of the text box should toggle showing a success indicator.
3.) All other entries into the text box should be considered as erroneous, and an error class should be appended respectively.
4.) Lastly, if the user clears the text box of any string they entered, then the box should revert its class to the original state and not persist with any of the above classes.
Here is Felix's revised jfiddle.
And purely the JS:
function checkSerial(el) {
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (!value) {
className = '';
}
else if (value.length === 14 &&
value.indexOf(prefix) === 0) { // match
className = 'success';
}
else if ((value.length >= prefix.length &&
value.indexOf(prefix) === 0) || // match
prefix.indexOf(value) === 0) { // partial match
className = 'warning';
}
document.getElementById('serial').className = 'serial-entry ' + className;
}
You could just use .indexOf and test that the string starts with the prefix:
document.getElementById('serial').className =
el.value.toLowerCase().indexOf('abcde') === 0 ?
'serial-entry success' :
'serial-entry warning';
For the three case, match, partial match, no match, you can check whether the input string is shorter than the prefix and apply the same logic, but vice versa:
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (value.length >= prefix.length) {
if (value.indexOf(prefix) === 0) { // match
className = 'success';
}
}
else if (prefix.indexOf(value) === 0) { // partial match
className = 'warning'
}
document.getElementById('serial').className = 'serial-entry ' + className;
DEMO
suggesting to use RegEx to match the prefix as follows:
var val = el.value;
if(val.match(/\bABCDE/g)!=null) {
document.getElementById('serial').className = "serial-entry success";
} else {
document.getElementById('serial').className = "serial-entry error";
}
this way you can easily validate if the input is starting exactly with 'ABCDE'.
You can change the RegEx to suite your requirements.
Try this:
if(el.value.toLowerCase().indexOf('abcde') == 0 && el.value.length == 14)
document.getElementById('serial').className = "serial-entry success";
else
document.getElementById('serial').className = "serial-entry warning";

HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?

This is strange behavior to me but on Webkit browsers (Chrome/Safari, not Firefox) if I include a space in a string of numbers in an <input type=number> then the value of that input is empty.
See this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/5/
Here's the code:
<input id='withOutspace' type='number' value='123'>
<input id='with_space' type='number' value='123 123'>
<button>click</button>
$('button').click(function(){
alert("withOut:"+$('#withOutspace').val()+" |||| with:"+$('#with_space').val());
});
If you go to this JSFiddle, you'll notice that the with_space input is empty. But if you put it in it a number that has a space or any non-numeric characters, the alert will say that input is empty.
Obviously, this is a disaster for form validation with credit card numbers, etc. so does anyone have a hack for this?
The hack is to use type="tel" instead of type="number".
This solves the 2 main issues:
It pulls up a number keypad on mobile devices
It validates (and is not empty) with numbers or non-numbers as input.
Please see this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/6/
I can suggest two ways.
1. Prevent chars in input
# updated to support more numerical characters related
$(window).keydown(function(e) {
if($('input[type=number]').index($(e.target))!=-1) {
if(
($.inArray(e.keyCode, [48,49,50,51,52,53,54,55,56,57,58,96,97,98,99,100,101,102,103,104,105,8,13,190,189]) == -1) // digits, digits in num pad, 'back', 'enter', '.', '-'
|| (e.keyCode == 190 && $(e.target).val().indexOf(".") != -1) // not allow double dot '.'
|| (e.keyCode == 190 && $(e.target).val().length == 0) // not allow dot '.' at the begining
) {
e.preventDefault();
}
}
});
or 2. Change input's type on fly
$('input[type=number]').focus(function() {
$(this).prop('type', 'text');
});
this allows to put whatever you want and change its type back onblur
$(this).blur(function() {
$(this).prop('type', 'number');
});
But still you cannot store nonnumerical values in input with type=number, so val() will always return you empty string if it meets char or space.
So, at least you have to remove all garbage with .replace(/[^\d]/g, '') - that means "remove all except numbers" before you change type back
In my example I show both methods + clear input values.
A way to control input number is to set it empty on blur when you can't read value
static formattedDecimalInput(input, maxScale, allowEmpty = true) {
input = $(input);
input.on("blur", function(e) {
var inputVal = input.val();
if(inputVal != "" || !allowEmpty) {
if(inputVal == "") {
inputVal = "0";
}
var number = Number(inputVal);
input.val(number.toFixed(maxScale));
} else {
input.val("");
}
});
}
You can formatted it by the way, and if you have invalid char on server side you can send a bad request response.
If you want a requiered field, you can just check if the input is empty with javascript before your server call
It is not really the answer of the initial question but I was looking for a user friendly control for this type of input when I arrived here
My hack for this problem includes the following (i use jQuery validators):
$(document).on('keyup', '[type="number"]', function () {
if (this.validity.badInput) {
$(this).attr('data-badinput', true);
}
});
Later in validator method i do this:
$.validator.addMethod('isInteger', function (value, element, parameterValue) {
if ($(element).attr('data-badinput')) {
//We know nasty browser always clears incorrect input, so empty string will look OK next time
$(element).removeAttr('data-badinput');
return false;
}
return !value || /^-?\d+$/.test(value);
});
You're setting a numeric input field to a string which is not a number. What did you expect to happen? The whole point is that these fields don't allow or accept non-numeric input. They are documented as only accepting a floating point value.
There is no "hack" available or required; the solution is to stop using a number input field for a value that isn't a number. Credit cards, phone numbers, etc; these things are not numbers. They contain digits as a subset of the valid characters, but they also contain completely non-numeric characters like spaces, hyphens and parenthesis. They need to be stored and treated as regular strings.
Use <input type="text"/>.

HTML textfield whose values cannot be 0 using Javascript

I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")

javascript validation to check # at start of user input: not email validation

I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }
Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}
Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)
You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.
function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.
Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.
apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.
In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)
Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.
Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.

Categories