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"]
Related
I have this JavaScript code
function checkTextField() {
var textVal = document.getElementById("textfield").value;
if (textVal == '', textfield.value.length <= 31)
{
alert('Wrong Key-Code. Key-Code must have 32 characters!');
}
else //Its all about how to decrypt a database file called ,,Salam Horia Allah,,!(good luck hackers)
{
{
var text = document.getElementById("textfield").value;
if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"
)
{
location.href = "http://79.115.70.31:8521/InWork/"
}
else {
alert("Wrong Key")
}
}
}
}
and here is what happen:
i have a textbox and a button,when i insert a key from if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
And when someone press that button, I want that script to check if one of that keys are in text field, if is true the request will send to another page, if is not true, show an alert.
But my problem is, whatever I write in that textbox it send me to that page, also I got an alert if textbox have <31 characters.
The comma operator works inside of an if clause, but it takes the last value, not a logical OR, which is here required.
(An input returns always a string and if empty, the string length is zero. A check for emptiness and a check for a length which is smaller than a value is superfluous, because the length check includes a zero length as well.)
if (textVal == '' || textfield.value.length <= 31)
// ^^
Beside that, I suggest to use an array for the valid keys for checking and check only if the value is in the array, then proceed or give an alert.
Another point is to assign the value of the input only once and use it in the whole function with the variable. Do not use a mixed style with a variable and document.getElementById("textfield").value together.
function checkTextField() {
var keys = ["3e6898f92134d05408dfed30b268d9d6", "fa0f82cc02a6cdc35072ee5ce2b0c379", "6a1df566fcaabca717aa1b81c3e0bd31", "dc0beea186c5f5c2110bedbeccc5a7aa", "1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40", "08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c", "ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11", "23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6", "teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy", "SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"],
text = document.getElementById("textfield").value;
if (keys.indexOf(text) !== -1) {
location.href = "http://79.115.70.31:8521/InWork/";
} else {
alert("Wrong Key");
}
}
Well you need to compare you tex with each key available so
function checkTextField() {
var textVal = document.getElementById("textfield").value;
var yourKeys =[ "3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"];
if (textVal == '', textfield.value.length <= 31)
alert('Wrong Key-Code. Key-Code must have 32 characters!');
else {
var text = document.getElementById("textfield").value;
var i = yourKeys.length;
while(i--){
if(text == yourKeys[i] )
location.href = "http://79.115.70.31:8521/InWork/"
else
alert("Wrong Key")
}
}
}
For example a correct format will be 2,545.39.
The user must not to be able to enter anything except for what is show above.
The user must also enter in a valid input, for example a user can't enter in a value such as 002453.23, so they can't have 2 0's next to each other.
Use the below code:
var regex = /^\d+(\.\d{1,2})?$/i;
var key = $('textbox').val();
if ((key.match(regex) != null) || (parseInt(key) != 0)) {
$('textbox').val(key.replace(/^0+/, ''));
alert('legal');
}
else {
alert('illegal');
}
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.
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";
Goal:
I dont wanna retrieving any data if the input data contain any alphabet.
Problem:
If I have input data "23w" in variable ddd, the process on convertion is accceptable to be "23" in the variable currentvalue.
I don't want it to be converted into number if the input data contain
any alphabet.
The sourcecode is writtin in jQuery and if possible it would be great to retreive the new solution in jQuery.
// Fullmetalboy
var ddd = $('#field_hourInput').val();
var currentValue = parseInt(ddd);
// Validating message
if(currentValue <= 0)
{
alert("Value must be positiv");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd != "") )
{
alert("value must contain numbers");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd == "") )
{
alert("value must contain value in the textbox");
nonError = false;
}
parseint() will return a number if the string begins with one, even if there is non-numbers following it. For example: http://jsfiddle.net/uQztw/
Probably better to use a regex. Something like
http://jsfiddle.net/uQztw/1/
You can use regex to validate that. Using regex with jquery. And using regex
[\d]
which will match any digit should do the trick.
Another way to convert string to int is Number(ddd), it does what you expect. But you could also check ddd through a regular expression, which feels better to me.
regexp-test: /^\d+$/.test(ddd)