I want to limit the number of letters at the beginning and end of the input value (e.g. QQ23F and SG21G) through JavaScript but I found that only one {} can be written in a pattern. Thanks for any help.
Here is my incorrect code:
var isValid = true;
var id=document.getElementById("pid").value;
if (!id.match(/[A-Za-z]{2}+[0-9]+[A-Za-z]{1}/)) {
document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
isValid = false;
}
You need to add the begging ^ and end $ signs
let isValid = true;
let id=document.getElementById("pid").value;
if (!id.match(/^([A-Za-z]{2}[0-9]+[A-Za-z]{1})$/)) {
document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
isValid = false;
}
And for everyone's sake use let not var
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");
}
}
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;
}
I have this javascript running on a html form. really struggling to get this working, Nothing pops up, no alerts at all. any help please. My code is probably terrible but I have only been using javascript for 4 weeks
function validate(form){
var vRunnerId = document.forms["submitrunnertime"]["RunnerId"].value;
var vEventId = document.forms["submitrunnertime"]["EventId"].value;
var vDate = document.forms["submitrunnertime"]["Date"].value;
var vFinishTime = document.forms["submitrunnertime"]["FinishTime"].value;
var vPosition = document.forms["submitrunnertime"]["Position"].value;
var vCategoryId = document.forms["submitrunnertime"]["CategoryId"].value;
var vAgeGrade = document.forms["submitrunnertime"]["AgeGrade"].value;
var vPB = document.forms["submitrunnertime"]["PB"].value;
var validFormat = /^\d{4}-\d{2}-\d{2}$/;
if (/\D/.test(vRunnerId)){
alert("Please only enter numeric characters only for your Runner ID");
return false;
}
if (/\D/.test(vEventId)){
alert("Please only enter numeric characters only for your Event ID");
return false;
}
if (!validFormat.test(vDate){
alert("Please enter date in YYYY-MM-DD");
return false;
}
return true;
}
I don't see your vDate being defined anywhere in that function, so it looks like you forgot to add that to your javascript.
You are grabbing the <input> value twice. Once here:
var vDate = document.forms["submitrunnertime"]["Date"].value;
and again in the check:
if (!validFormat.test(vDate.value)){
You're trying to find the .value of a .value which I would assumed would throw en error.
I have a problem here with validating user's input in textarea.
A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.
Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page.
Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??
PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side
var STRING_MAX_LENGTH = 10;
var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );
$.each( array, function() {
if ( this.length >= STRING_MAX_LENGTH ) {
if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\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D7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i . test( this ) ) {
alert( this + ' is an URL' );
} else {
alert( this + ' is not an URL' );
}
}
});
http://jsfiddle.net/vVYAp/
function validate()
{
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var wordLengthExpr = /\b[^\s]{50,}\b/;
var regex = new RegExp(expression);
var wordLengthRegex = new RegExp(wordLengthExpr);
var t = $("#myTextarea").val();
if (t.match(regex) || !t.match(wordLengthRegex))
{
//valid
}
else
{
//throw error
}
}
This is a two step process:
Determine if any words are too long.
If so, determine if they are valid URLs.
var validateWordLength = function (str) {
var maxLength = 50, // or whatever max length you want
reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
words = str.split(/\s+/),
i;
for (i = 0; i < words.length; i += 1) {
if (words[i].length > maxLength) {
// test for url
// but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
// testing for url may not be fruitful
if (!reURL.test(words[i])) {
return false;
}
}
}
return true;
};
try this
var value = Your text;
var result = value.replace(" ","");
if(value.length == result .length)
//not valid
else
//valid
You can get length of each word, and then can decide whether to allow the user or not -
var arr = text.split(' ');
$.each(arr,function(){
console.log(this.length);
// check valid word length
});
http://jsfiddle.net/mohammadAdil/cNZtn/
If you use the jQuery validate plugin you can add a method to it:
jQuery.validator.addMethod("samechars", function(value, element) {
return this.optional(element) || !/([a-z\d])\1\1/i.test(value);
}, "Invalid input");
If you want to use jQuery you can use the following:
$("form").submit(function(e){
var $textarea = $('#msg'),
maxWordLength = 20;
var value = $textarea.val().split(' '),
longWord = false;
for(var n = 0; n < value.length; n++) {
if(value[n].length >= maxWordLength)
longWord = true;
}
if(longWord) {
alert('Too long word');
return false;
}
});
Here is a fiddle:
http://jsfiddle.net/pJgyu/31286/