I tried using following method to ban users from leaving only space in the input area with no luck:
method one:
var formSub = $('#formsub').val();
if (formSub == null || formSub == "") {
return false;
}
method two:
if (formSub.trim() == "" || formSub.trim() == " ") {
return false;
}
method three:
if ($.trim(formSub) == "" || $.trim(formSub) == " ") {
return false;
}
Any thought? :)
Use a simple regexp:
/\S/.test(formSub)
where \S refers to any non-white space character.
This removes the dependency on trim (not found in IE<=8) and/or jQuery.
It should be formSub == null || formSub.trim() === "".
=== and == isn't exactly the same. == "" can means true, and any string is "true".
Try:
if (formValue.length === 0 || !formValue.trim()) {
return false;
}
Haha! This is a good one you actually walk around the solution all along.
So here for example, you actually already trimmed all the spaces by using .trim()
if (formSub.trim() == "" || formSub.trim() == " ") {
return false;
}
Correct would be just,
if (formSub == " ") {
return false;
}
This will be the most useful, it passes if someone actually wrote something different from spaces, or other invisible characters ;)
Google "Javascript Regex for more info"
if (/\S/.test(formSub)) {
// String is not empty
}
else{
// String is empty and not usefull
}
Cheers ;) ! +1 Appreciated
Related
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"]
I am trying to compare value of TestScript with string "Investisseur" But this seems not working and I don't go into the if statement.
console.log(GM_getValue(TestScript));
if(GM_getValue(TestScript) == "Investisseur")
{
//Should be there
}
console.log(GM_getValue(TestScript)); returns :
So the if condition would return true and not false .. What Am I doing Wrong ?
EDIT
It seems like the check before reset my #GM_getValue:
if(GM_getValue(TestScript) == "Investisseur" || GM_getValue(TestScript) == null || GM_getValue(TestScript) == undefined ){
GM_setValue(TimeoutMain, 1000)
}else if(GM_getValue(TestScript) == "Emetteur"){
GM_setValue(TimeoutMain, 10000)
}
Any Idea why ? When I try to Console.log after this it display nothing .. Why is the value deleted ?
Maybe more understandable with a screen there :
TestScript might have extra spaces.
trim() removes leading and trailing whitespace.
Try replacing:
GM_getValue(TestScript)
with:
if (GM_getValue(TestScript).trim() == "Investisseur")
I need to check to see if a variable is null or has all empty spaces or is just blank ("").
I have the following, but it is not working:
var addr;
addr = " ";
if (!addr) {
// pull error
}
If I do the following, it works:
if (addr) {
}
What I need is something like the C# method String.IsNullOrWhiteSpace(value).
A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:
function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}
...then:
var addr = ' ';
if(isEmptyOrSpaces(addr)){
// error
}
* EDIT *
Please note that op specifically states:
I need to check to see if a var is null or has any empty spaces or for that matter just blank.
So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.
if (addr == null || addr.trim() === ''){
//...
}
A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).
You can use if(addr && (addr = $.trim(addr)))
This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.
Reference: http://api.jquery.com/jQuery.trim/
Old question, but I think it deservers a simpler answer.
You can simply do:
var addr = " ";
if (addr && addr.trim()) {
console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");
}
Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
You can create your own method Equivalent to
String.IsNullOrWhiteSpace(value)
function IsNullOrWhiteSpace( value) {
if (value== null) return true;
return value.replace(/\s/g, '').length == 0;
}
isEmptyOrSpaces(str){
return !str || str.trim() === '';
}
When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:
function isNullOrWhiteSpace(str){
return str == null || str.replace(/\s/g, '').length < 1;
}
isEmptyOrSpaces(str){
return str === null || str.trim().length>0;
}
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* #param {any} str string to be evaluated
* #returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
function isEmptyOrSpaces(str){
return str === null || str.match(/^[\s\n\r]*$/) !== null;
}
I use simply this and this works for me most of the time.
it first trim the white spaces and then checks the length.
if(value.trim().length === 0)
{
//code for empty value
}
Maybe it's easier this way
if (!addr?.trim()){
//error
}
Based on Madbreaks' answer, and I wanted to account for undefined as well:
function isNullOrWhitespace(str) {
return str == null || str.match(/^\s*$/) !== null;
}
Jest tests:
it('works for undefined', () => {
expect(isNullOrWhitespace(undefined)).toEqual(true);
});
it('works for null', () => {
expect(isNullOrWhitespace(null)).toEqual(true);
});
it('works for empty', () => {
expect(isNullOrWhitespace('')).toEqual(true);
});
it('works for whitespace', () => {
expect(isNullOrWhitespace(' ')).toEqual(true);
// Tab
expect(isNullOrWhitespace(' ')).toEqual(true);
});
You can try this:
do {
var op = prompt("please input operatot \n you most select one of * - / * ")
} while (typeof op == "object" || op == "");
// execute block of code when click on cancle or ok whthout input
The regex below works nice except I need only one dot (.) at the end for nameserver. For example if user submit ns1.hello.com there will be error. Accepted format is with dot at the end like this ns1.hello.com. Help me please. Thank you.
<script type="text/javascript">
function validSubdomain() {
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
var val = document.getElementById("nameserver").value;
var val2 = document.getElementById("nameserver2").value;
if(val == '' && val2 == ''){
alert("Please fill in the name server");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val == ''){
alert("Please fill in the name server 1");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val2 == ''){
alert("Please fill in the name server 2");
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
var parts = val.split('.');
var parts2 = val2.split('.');
if (parts.length < 3)
{ alert('invalid nameserver format')
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
else if (parts2.length < 3)
{ alert('invalid nameserver 2 format')
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
if( !re.test(val)) {
alert("invalid nameserver 1 format");
return false;
}
else if( !re.test(val2)) {
alert("invalid nameserver 2 format");
}
else{namaform.submit();}
}
</script>
Two things wrong with:
if(re.test(val && val2)) {
alert("valid format");
}
if(!re.test(val && val2)) {
alert("invalid format");
}
First of all, have you never heard of else? It's there specifically so you don't have to repeat a test in the negative.
Second, you are trying to && together the two string and then passing the resulting boolean to re.test(). Since a boolean converts to the string "true" or "false" it will never ever match.
Change to:
if( re.test(val) && re.test(val2)) {
alert("valid format");
}
else {
alert("invalid format");
}
Also note that your regex is wrong. It would accept a..b as input, which is clearly not valid. Try this instead:
var re = /^([a-z0-9-]+\.)+[a-z]{2,3}\.$/i;
This will broadly match most domains with unlimited number of subdomain levels, provided there's a . at the end.
EDIT to disallow - at the front of a section:
var re = /^([a-z0-9][a-z0-9-]*\.)+[a-z]{2,3}\.$/i;
It sounds like you're just saying that this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/;
needs to be this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
?
If you want to match a special character in a regex (also referred to as 'metacharacters') you need to escape it with a backslash. So, just before the $ in your regex, include
\.
to match the dot at the end of the string.
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.