Check if value matches mask - javascript

I have a input that has a mask of date like __/__/____. I stored it in a variable. Is there a way to detect if it matches the mask properly?
The event is binded on blur, so sometimes it is returning values like 22/12/___.
Is there a way to detect if it definitely fits the scheme with integers and slash only or doesn't?
$('#btn').click(function() {
value = $('#my-input').val() // should be in this format 99/99/9999 and not 12/12/12__
// here I need to check if it is in right format.
if (checkFormat(value)) {
}
}

You can use regex to validate this.
var regex_check = /^\d{2}\/\d{2}\/\d{4}$/ ;
//Edit - Vanilla JavaScript
function foo(date) {
var regex_pattern = /^\d{2}\/\d{2}\/\d{4}$/ ;
var check = new RegExp(regex_pattern);
var res = check.test(date);
// return true or false
return res;
}

Use match() with the following regex : ^\d{2}\/\d{2}\/\d{4}$
your code will be like :
$('#btn').click(function() {
value = $('#my-input').val();
if (value.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
alert("match");
}
else {
alert('the value does not match the regular expression');
}
}

Related

how to pass the json data inside javascript regex? and also validate password in sequence

I am trying to validate the password using javascript regex. Now I want to validate two lower case letters (2 small letters) which is coming from json.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password");
var lowerCaseLetters = /[a-z]{2}/g;
if(psw.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}
In the above code I am setting up a variable "Lcase" to json data and now I want to replace "{2}" (inside regex) with that variable "Lcase" coz the "Lcase" variable is dynamic. If I am doing something wrong then please guide me to come out of this problem.
I want to validate small case letters which is coming from json(dynamic number) to see how many small letters are there in the password string.
For your information the below code for password length is working.
if(psw.value.length >= jsonData.MINLEN_RANGE) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
If define your regular expression using RegExp, you can define {2} using Lcase.
This code also includes the question posted on the comments bellow.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password").value.replace(/([a-z])\d+/g, '$1');
var lowerCaseLetters = new RegExp('[a-z]{' + Lcase + '}', 'g')
if(psw.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}

JavaScript RegExp returns false in every valid and invalid inputs

In my JSP page I have one table in that one of the column is for the Time shown in the HH:mm format and the datatype is String (I converted it from Date to String in server). Now I am applying the Inline table row editing using the Jquery plugin Tabledit.
While I edit the column and before sending to the server I am checking it with RegExp.
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14:34";
if (timeRegEx.test(inTime[1])) {
alert("Matched");
//return true;
} else {
alert("Not Mateched");
//return false;
}
I have checked the validity of the RegExp in some onilne resources and it is correct.
But in my case in every valid and invalid input it always goes to the else block.
And the more thing is that the while I print the value of the inTime[1] in alert. it gives the output like : 14%3A13
So I also replaced the : with %3A in RegExp but it also not worked.
So please tell me where I am going the wrong and what is the correct solution.
Edit:
Here : interpreted as %3A so may be this creates the problem.
Here inTime is array which get values from the table row.
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14%A334";
if (decodeURIComponent(timeRegEx.test(inTime[1]))) {
console.log("Matched");
//return true;
} else {
console.log("Not Mateched");
//return false;
}
Does this suite your needs?
var regex = /^[12]?\d:[012345]\d$/,
tests = [
'56:12',
'03:68',
'2:49',
'12:59',
'23:00',
'abcs',
'12,23'
];
tests.forEach(test => {
var isValid = regex.test(test);
console.log(`is ${test} valid: ${isValid}`);
});
As I mentioned in the question that the array variable inTime[1] get the data from the HTML table. It takes the: as the %3A, so it creates the problem to test the RegExp.
#Spanky give me hint to try decodeURIComponent(timeRegEx.test(inTime[1])) but it also not worked for me.
So I have slight modify his solution and applied the decodeURIComponent() to only inTime[1] Variable. This worked for me.
The solution code snippet is as follow:
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14%3A34";
if (timeRegEx.test(decodeURIComponent(inTime[1]))) {
console.log("Matched");
//return true;
} else {
console.log("Not Mateched");
//return false;
}

Javascript Regexp Format

I'm a beginner in JavaScript. I tried every tutorial/site and couldn't find an answer. I couldn't understand some examples.
I want to put a specific format and validate if the users input is correct.
Here is my code:
var expD = document.getElementById("ccN");
var re = new RegExp("[0-9][0-9]/[0-9][0-9]");
if (re.test(expD))
bootbox.alert("Correct");
else
bootbox.alert("Wrong");
expD is DOMElement, you cannot use it as if it is string
You need to bind event on textbox/button, to check if the value entered by user is in valid format
The regular expression needs ^ and $ anchors, if you want to check if the complete string is in the valid format
In your case expD is a dom element, I think you need to get the value and test it
function testit() {
var expD = document.getElementById("ccN").value;
var re = /^\d{2}\/\d{2}$/;
if (re.test(expD)) {
alert("Correct");
} else {
alert("Wrong");
}
}
<input id="ccN" />
<button onclick="testit()">Test</button>

JavaScript First Letter Capitalisation Not Working

Firstly, this is my first time working with JavaScript so it is probably just me missing something very simple.
All I want to do is get the value of a text box and make an alert with the first letter capitalised. I have everything working, the first letter isn't actually being capitalised.
This is how I am calling the function:
else
{
input = document.getElementById("search").value;
'input'.search();
alert(input);
}
This is the function it self:
function search(string)
{
return string.charAt(0).toUpperCase();
}
this is the correct code
else
{
input = document.getElementById("search").value;
input =search(input);
alert(input);
}
Try this:
input = search(input);
Instead of:
'input'.search();
You aren't changing input at all. Try:
else
{
input = document.getElementById("search").value;
alert(search(input));
}
If you want to permanently change input Try:
else
{
input = document.getElementById("search").value;
input = search(input);
alert(input);
}
A couple of things wrong here,
firstly,
search(input)
instead of
'input'.search()
secondly,
string is immutable so you'll have to do,
input = search(input);
alert(input);
.
.
.
function search(str) {
return (str.replace(str.charAt(0), str.charAt(0).toUpperCase()));
}
Your question is not pretty clear to me, but I assume that you want, if your input string is "hello" , you want the output as "Hello".
Try this
call the method and alert the message:-
alert(search(input));
in the method:-
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase()+this.slice(1);
}
var searchField = document.getElementById("search");
var query = searchField.value;
searchField.value = query.capitalize();
function search(query) {
// query api or something...
}
The answers are correct, but you will have only the first letter in the alert box.
If you don't want only the first letter, here is the solution:
function search(string)
{
return string.substring(0,1).toLocaleUpperCase() + string.substring(1);
}
From https://stackoverflow.com/a/30123193/2379208

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources