My name, e-mail and check boxes follow the same js pattern and the validation works great but birthday will not validate. I start by stripping the white space so they can't leave it blank, then using a regex to determine if its valid. Is my regex wrong?
validate: function (attrs, options)
{
var errors = [],
pattern = '/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/',
isValidBirthday = attrs.birthday && attrs.birthday.replace(/\s/g, '') && attrs.birthday === ('pattern');
if (!isValidBirthday)
{
errors.push(
{
"birthday": "Must have a valid birth date."
});
}
if (errors.length)
{
return errors;
}
},
You are using the regular expression wrong. Try the following instead, noting the lack of
'' around the regex, and the use of .test method on the pattern.
var errors = [],
pattern = /^(0[1-9]|1[0-2])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$/,
isValidBirthday,
cleanedBirthday;
cleanedBirthday = attrs.birthday && attrs.birthday.replace(/\s/g, '');
isValidBirthday = pattern.test(cleanedBirthday)
Related
I want to use regex patterns in the answers provided to this question How to validate an email address in JavaScript?
but all of them show red squiggly line unde at sign #. What's the reason and how to solve this problem?
/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
This is my js function:
<!--language: lang-js-->
$('input.filled-in').change(function () {
check_bname(this, $(this).next().next().children().first());
})
function check_bname(input, errorMsg) {
var patternEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
$elemInput = $(input),
$elemError = errorMsg,
$inputVal = $(input).val(),
attrName = $elemInput.attr("id");
if($elemInput.hasClass("filled-in"))
{
patternMatch = $inputVal !==''&& patternEmail.test($inputVal);
}
$elemError[patternMatch ? 'hide' : 'show']();
}
if (!patternMatch) {
if($elemInput.hasClass("filled-in"))
{
$elemError.html($inputVal === '' ? "Should not be empty" : "Use valid form of Email Address e.g (example#example.com)");
}
}
The regex is OK. This must be wrong syntax checking. Many IDEs show warnings or errors when using regex in this form in JavaScript. You can supress the warning or change the regex like this:
var patternEmail = new RegExp('^(([^<>()\\[\\]\\.,;:\\s#\\"]+(\\.[^<>()\\[\\]\\.,;:\\s#\\"]+)*)|(\\".+\\"))#(([^<>()[\\]\\.,;:\\s#\\"]+\\.)+[^<>()[\\]\\.,;:\\s#\\"]{2,})$','i');
patternEmail.test($inputVal);
Note: \ have to be escaped in this form. Use \\ instead
I would supress the warning because the other form is better in this situation.
What IDE is showing the red squiggly line?
I do not see any problem with any characters in your regex.
This JS sample uses your regex.
function getPattern()
{
var pattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern;
}
var patn = getPattern();
var estr = "www.google.com";
var match;
if ( match = estr.match( patn ) )
console.log( match[0] );
else
console.log( "No match" );
I need some help creating regexp. It's just I don't quite understand how to create a regexp. How do i create a validation for username with some rules like this
only Uppercase, lowercase, underscore(_) and dot(.) are allowed
start with an underscore(_)
I've already tried some regexp from mozilla developer site, but it doesn't seems right
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
I expect some username like so
_username = true
_username1 = false
.username = false
username = false
and also are there any sites for me to understand how to create regexp, because I got some more thing to do with it
function validuser(username) {
var msg = "valid";
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
return msg;
}
console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
When creating regex, you can help yourself using https://regex101.com/.
That said, here is your regex :
function test(username) {
const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');
// Alternative version considering #thomas points
// const regex = new RegExp('^_[A-Za-z._]+$', 'i');
return regex.test(username);
}
console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));
I have a regex which checks the inputText is in valid url format or not.
And working almost good:
checkUrlFormat() {
const pattern = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
But i need to make that pattern shorter so I have written a regexp in https://www.debuggex.com/#cheatsheet as
(((http|https)(://))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]
but it is in javascript format and i could not find how to use that string with the code above. When i directly copy paste it, it is giving syntax error. How can i combine them.
checkUrlFormat() {
const pattern = /^(((http|https)(:\/\/))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
So I currently have this method for enforcing strong passwords:
$.validator.addMethod('goodPassword', function(value, element){
return this.optional(element) ||
value.length >= 6 &&
/\d/.test(value) &&
/[a-z]/i.test(value);
}, 'Your password sucks boy, you need at least 6 char and both number and char in that motherf.')
I want to create something similar for my usernames to limit them only to letters, numbers, dashes, underscores and periods. I can't seem to figure out how to go about it. I read about regex a little but still couldn't figure out how exactly I should go about my code.
This is what I currently have:
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) ||
value.length >= 4 // && or ||, not really sure what to put here
//something to check if entered data contains anything other than letters, numbers, dashes, underscores and periods
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.')
Can someone show me the way please?
Here's the code that uses Javascript regex functionality
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) || value.match(/^[\w.-]{4,}$/m)
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.')
As correctly noted by #rock321987, it'd still allow ...-... and other strange usernames.
you can use this function and set your custom illegal charters :
function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
alert(error);
return false;
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = 'Yellow';
error = "The username is the wrong length.\n";
alert(error);
return false;
} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
alert(error);
return false;
} else {
fld.style.background = 'White';
}
return true;
}
I got this Regex to work and based off the jQuery Validator documentaion.
/^[a-z|A-Z]|\d|_|-|\./m
Here is how it look in the code. jQuery validator addMethod
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) || /^[a-z|A-Z]|\d|_|-|\./.test(value);
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.');
I write use thie site to write my regular expressions regex 101
I ran it against these strings.
var str2 = 'uerhyeiufhsniufhsdJSHNAJDHJS09i304584305i4309SKA()*^&85$674&_-.dsf%#$fdfIIJ76..';
var str2 = 'dskfjdkaAHDNsfj34-2sds3432_-.*()$%#545#';
I am using custom[email] rule for email validation in Jquery Validation Engine. What I want is, I want regex that validates email with blank value also. If value is blank then also it should show error message.
I dont want to use required rule.
Here is the custom rule given in Jquery Validation Engine
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"alertText": "* Invalid email address"
}
Please help me out.
This should work
^([^#]+#[^#]+)?$
It will validate
empty strings, OR
strings that have one or more non-#
followed by a #
followed by one or more non-#
try this
here is the fiddle
var emailReg = /^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/;
function checkEmail(email) {
var reg1 = /(#.*#)|(\.\.)|(#\.)|(\.#)|(^\.)/; // not valid
var reg2 = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
if (!reg1.test(email) && reg2.test(email)) {
return true;
}
else {
return false;
}
}