Validation on onKeyUp - javascript

I need to do validation onkeyup and onsubmit.
I have field called CVV which accepts 3 or 4 digits numbers, so i'm using '^(d){3,4}$'.
This pattern works properly when i did in onsubmit function, but in onkeyup function i get always false even i enter 3 digits number.
<input type="text" onkeyup="callonkeyup(this,'First Name','^(d){3,4}$')" value="First Name">
function callonkeyup(tag,defaultValue,pattern){
var isValidate = validate(pattern,trim(tag.value),defaultValue);
console.log("==isValidate=="+isValidate+"==tag.value=="+tag.value+"===pattern==="+pattern);
}
function validate(pattern,value,defaultVal){
var returnValue = false;
if(value && value != defaultVal){
while(pattern.indexOf('\\\\') != -1) {
pattern = pattern.replace('\\\\', "\\");
}
var testPattern = new RegExp(pattern,"");
if (testPattern.test(value)){
returnValue = true;
}else{
returnValue = false;
}
}
return returnValue;
}
function trim(value){
return value.toString().replace(/^\s+|\s+$/g,'');
}

Working DEMO
You need to escape back slash (\) so your regular expression should be ^\\d{3,4}$ instead ^(d){3,4}$

You need to add a \ in front of the d, without it the d is represented as the character d and not a numeric value. Here's the expression you should use ^\d{3,4}$.
EDIT
The first part was on track, but I missed that you were passing the pattern as a string to another function. If you were to run new RegExp('^\d{3,4}$', "") it would work, but because it was being passed through a function, the \ character was being removed. In order to pass a string with a backslash in it, you need to escape the slash with another back slash like so \\. This means your new expression should be ^\\d{3,4}$.
When developing regular expression I usually use something like http://regexpal.com/ to help test them. Keep in mind that for this one you would have to check the ^$ match at line breaks (m) box for it to match multiple tests on multiple lines

Related

Regular expression not supporting line skipping \n

I'm trying to find the right regular expression for a number with a line skip at the end ( \n ) but every time it's not working.
My regular expression is /^\d+(\n)$/.
EDIT : The text area contains :
22\n
33
Here's my code ( I'm trying to validate what's in the textarea and it's only numbers going there with \n at the end of each lines ) :
function valideChamp()
{
var rExp1 = /^\d+(\n)$/;
var aChamps = document.querySelector("textarea").value;
if (rExp1.test(aChamps.value)==true){
alert("Valide")
}
else {
alert("Invalide")
return false;
}
}
If you want to check for any line containing only a number on it, you can use:
/(^|\n)\d+(\r?\n)/
If you just want to check that there's only a number, and then a newline, and nothing else:
/^\d+(\r?\n)$/
(which is what you were checking for, but that's an odd input pattern.)
If you want to make sure textarea ONLY has lines that are numbers, it might be simpler to check that string.replace(/[0-9\r\n]/g, '') == ''. This will confirm if it contains only numbers and newlines.
Remove ".value"
from this line:
if (rExp1.test(aChamps.value)==true){
You're using $ and \n together which is slightly redundant. Try
/\d+$/gm
where g = global flag and m = multiline flag. Note this will match multiple lines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Regular expression in JavaScript not working

Regular expression not able to read complete string, only working correct with single character.
var abc = "ab";
var patter = /^([a-z0-9A-Z])$/;
if (patter.test(abc)) {
console.log('yes');
} else {
console.log('no');
}
You must set a quantifier when you don't want just one character.
Add a * to match zero or more character (or a + if you want to be sure there's at least one character);
var patter = /^[a-z0-9A-Z]*$/;
Note that I removed the parentheses : they're useless with the test method.

jQuery regexp validation

I would like to validate user input client side with a little jQuery function that is called onsubmit on my form. I want the field #fname (first name) to only allow a-z, A-Z and space. The return false is supposed to be stopping the form from submitting.
function validateregister(){
if (!($("fname") =~ [a-zA-Z ])) {
return false;
}
}
This is my HTML:
<input type="submit" value="Join now!" id="registersubmit" class="paddingoutline2" onsubmit="return validateregister()">
Of course, i'm going to validate the user input on the server side later on. When I submit the form, it gives me an "internal server error". This makes me think that I made an error in my function validateregister(). Is there anything wrong? If the I'm pretty new to jQuery so any help is appreciated.
Thanks!
What you want is
function validateregister(){
return /^[a-zA-Z ]+$/.test($('#fname').val());
}
Apart fixing the selector suggesting the use of the val and test functions, I took the liberty to change the regex :
^ and $ force the test to cover the whole string
the + requires at least one character
But are you aware that this regex might be too strict if you want people to type their real first name ? Yours, for example, would not pass...
You have to use regex this way:
function validateregister(){
var nameRgx = /[a-zA-Z]/;
var phoneRgx = /[0-9]/;
if (!nameRgx.test($("#fname").val())) {
return false;
}
if (!phoneRgx.test($("#phone").val())) {
return false;
}
}
And make sure to refer your elements with Either with # id notation or . class notation. In your code you are not referencing your elem in a proper way.
^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression;
also forces minimal matching when an expression might
match several strings within a search string.
More Info about Regex writing

check a textbox for invalid characters using js and regular expressions

I am having a hard time figuring out how RegExp work.
I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:
<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">
Now, what I do is create an input textbox which will run a js function whenever its content is changing.
<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else {
// Regex stuff goes in here
}
}
Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?
If you want the regex to check for invalid characters in the field, you can use this.
^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.
You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:
ValidationExpression="^[^#%&*:<>?/{|}]+$"
EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:
new RegExp(validationExpressionGoesHere);
[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else if(val.match(/[^#%&*:<>?/{|}]+/)) {
// Valid
}
else {
// Invalid
}
}

javascript pattern matching

matchArray becomes null for input like asklas#(((# How do I correct this behavior? I only want to allow characters and numbers..
function validateName(name) {
debug(name);
var namePat = /^(\[A-Za-z0-9]*)$/ ;
var matchArray = name.match(namePat);
if (!matchArray){
debug ("Invalid name,", name );
return false;
}
return true;
}
There is one erroneous backslash in your regex. It should be
var namePat = /^[A-Za-z0-9]*$/;
(and you don't need the capturing parentheses, either).
Not sure what you want in this case... if you want a boolean output, use .test:
namePat.test(name)
... but null will work for your test (!matchArray) just fine.
It does seem like you have a typo in your regular expression - you'll want to get rid of the backslash before the opening bracket...

Categories