I'm trying to create a regular expression for a field with the following conditions.
no blank should allowed
special characters are not allowed apart from underscore, hyphen, period.
Alphabets and numeric are allowed.
I have created my own regular expression its working fine but it is accepting one special character in the beginning
like if i enter # or $wer in the field it will work and data will be saved.
like if i enter ## , %^hihf or qwerty#333 in the field it will show an error.
find below code.
$.formUtils.addValidator({
name: "username",
validatorFunction: function(a) {
return !!a.match((/^[^\s][ A-Za-z0-9_./-]*$/))
},
errorMessage: "Please enter a valid Username (Special characters are not allowed apart from Underscore(_), Hyphen(-) and Period(.)) ",
errorMessageKey: "badname"
}),
I think you need more than just a Regex for some of these conditions. Try:
validatorFunction: function(a) {
var rgx = /^[A-Za-z0-9_./-]+$/;
var trimmed = a.trim();
return trimmed.length > 0 && rgx.test(trimmed);
}
This would solve the issues of blanks, special characters, and forcing alphanumerics...
Your [^\s] at the start of the regex means any character other than a space is valid, hence "#" will match.
I think you want to use something like this to allow leading and trailing whitespace and force at least 1 valid character:
return !!a.match((/^\s*[A-Za-z0-9_\./\-]+\s*$/))
Related
In our project, we use this regular expression to validate emails:
"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,7}|[0-9]{1,3})(\]?)$"
But it allows non English characters.
For example:
"مستخدم#mail.com"
"userمحمد#mail.com"
"userName#خادم.com"
are valid emails.
How to add another rule to this expression to limit inputs to English letters only?
You can omit the alternation | in your pattern, and there is an optional closing bracket \]? which I think you don't need in an email address.
This part in the regex with Javascript and C# [\w-\.] does not seem to be a valid range in a character.
Instead of using \w you can use [A-Za-z0-9] to match ASCII chars and digits 0-9 in C#.
If you don't want to match consecutive dots or hyphens, you can use a pattern like this and then extend it if you have more characters that you want to allow:
^[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*#[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*\.[a-z]{2,}$
Regex demo
Note that this only validates an email address of this format.
Can do like this
string[] StrInputNumber = { "pradeep1234#yahoo.in", "مستخدم#mail.com'", "userمحمد#mail.com", "userName#خادم.com" };
Regex ASCIILettersOnly = new Regex(#"^[\P{L}A-Za-z]*$");
foreach (String item in StrInputNumber) {
if (ASCIILettersOnly.IsMatch(item)) {
Console.WriteLine(item + " ==> valid");
}
else {
Console.WriteLine(item + " ==>not valid");
}
}
Output
for some basic explanation about regex Click Here
You can use this website to test your regular expression
If you don't need to keep your current expression you can use this one instead:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.
I tested it with your examples and it works as you want.
Problem: I'm trying to validate when the user only inputted special characters without typing any number with it.
I'm using this expression
/^\+?[0-9 \.-]+$/
to accept only '+' sign, numbers, dots, hypens, and spaces when validating fax. This is working fine.
But with that expression the user can input -------------- without typing any number and is accepted because it contains hypen.
Question: Is there's a way to check if the input contains number? not just all special characters?
UPDATE:
This is an example of valid accepted input.
+1-2 12-98765.43 > the requirement is it should only accept '+' sign, hypen, numbers, spaces and dots.
Probably the easiest option is to have additional regex checks for each condition. E.g. have a regex check for just the presence of numbers /[0-9]/ and another check for just the presence of special characters /[ +.-]/. Run these only after testing that nothing undesirable exists in the string.
var whole = /^\+?[0-9 \.-]+$/
function validate(input) {
// input only contains valid things
if (!input.test(whole)) { return "Input must contain only numbers, spaces, and + . or -"; }
// input contains each required thing
if (!input.test(/[0-9]/)) { return "Number required"; }
if (!input.test(/[ .-]/)) { return "Special character required"; }
// You can also test the first character of the string with charAt()
if (input.charAt(0) !== "+") { return "Input does not begin with +"; }
return "Valid input";
}
I notice that your regex tests for zero or one plus, followed by a character in the list [numbers, spaces, periods, or hyphens]. Do you mean to test for any number of pluses? The regex I've posted (/[ +.-]/) should work for all the characters you want to allow.
I'm not sure this is what you're looking for, but if you want to verify that a specific single character or pattern exists in a string, you can use indexOf:
// Require at least one hyphen
if (input.indexOf("-") === -1) { return "Please include a hyphen"; }
Update: If, as in your example, there is only one plus and it is at the beginning, then you do indeed want the \+? bit. However, you don't need to escape the period inside of square brackets. Supposing the plus were required, you could use charAt to test this. See updated example.
Just add a lookahead.
^(?=.*[0-9])\+?[0-9 \.-]+$
See demo.
https://regex101.com/r/eB8xU8/9
This is an example of valid accepted input.
+1-2 12-98765.43 > the requirement is it should only accept '+' sign, hypen, numbers, spaces
Accepted input appear to accept . character as well ?
Try ^(\+\d-\d \d{2}-\d+)(?:\.\d+|$)
<form>
<input type="text" pattern="^(\+\d-\d \d{2}-\d+)(?:\.\d+|$)" required />
<input type="submit" />
</form>
I am using jquery validation plugin for validating my input fields.
I have a field that should accept:
a) letters [a-zA-Z]
b) letters with numbers [a-zA-Z0-9]
c) no special characters
So:
ADFad1334 or 43545SFDDFdf454fgf : is correct, since we have letters and numbers
asdadadASD : is correct, since we have only letters
12312342 : NOT correct, since its only numbers
sdff23424#$ : NOT correct, since there are special characters (in this example # and $)
The code i used is the one below:
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z]*$/img.test(value) || /^[a-zA-Z0-9]*$/img.test(value);
},"Must contain at least a letter and/or number(s). No other characters are allowed");
And then:
$('#RegistrationForm').validate({
rules: {
fieldname: {
atLeastAletter: true
},
.....
The problem with this regular expression is that if the input is only numbers (ex. 3434224), it will accept it and pass validation.
What is the problem?
Thanks in advance.
or this pattern
^(?=\S*[a-zA-Z])[a-zA-Z0-9]+$
Demo
^ # Start of string/line
(?= # Look-Ahead
\S # <not a whitespace character>
* # (zero or more)(greedy)
[a-zA-Z] # Character Class [a-zA-Z]
) # End of Look-Ahead
[a-zA-Z0-9] # Character Class [a-zA-Z0-9]
+ # (one or more)(greedy)
$ # End of string/line
/^\w*[a-zA-Z]+\w*$/
That should match any string with only letters and numbers, but it must contain at least one letter.
sadAddsa // Pass
98463298 // Fail
jdsH98sd // Pass
987Fkjd89 // Pass
jfk!jhj // Fail
kjhgh8768!# // Fail
A8 // Pass
8S // Pass
B // Pass
7 // Fail
B_bkfd86jh // Fail (Using the regex in the edit)
Edit: As Alpha Bravo pointed out. This will match underscores too. If you don't want underscores /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/will only match letters and numbers, only if it contains one letter.
If you want want to go with all HTML5 look at this fiddle: http://jsfiddle.net/bud68oho/2/
This fiddle uses the required and pattern attributes to validate the form. The required attribute does not allow the form to post if the input is not filled in. The pattern attribute allows you to implement regex for matching. If the input does not meet the requirements of the regex then the form will not post.
The only gotcha with this approach is browser compatibility. Make sure to test this method with your target browsers. The above example works in the latest version of IE and Chrome, I am unable to do any further testing.
/^[a-zA-Z0-9]*$/img.test("1") is true, so just take with two regexp for both:
return /^[a-zA-Z]*$/img.test(value) || (/[a-zA-Z]/img.test(value) && /^[a-zA-Z0-9]*$/img.test(value))
or like this:
return /^[a-zA-Z]*$/img.test(value) || (/^[a-zA-Z0-9]*$/img.test(value) && !/^[0-9]*$/img.test(value))
Notice: If you put i after the regexp (img) you just have to put a-z or A-Z, it's not case sensitive.
Ohter notice: you allow empty strings "" with those regexps.
I think you may need to do a positive alphanumeric check and a negative check for the numeric only case.
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z0-9]+$/img.test(value) && ! /^[0-9]+$/img.test(value)
},"Must contain at least a letter and/or number(s). No other characters are allowed");
I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.
function validText(field)
{
var re = /[a-zA-Z0-9\-\_]$/
if (field.value.search(re) == -1)
{
alert ("Invalid Text");
return false;
}
}
A valid input would be something like
'Valid_Input123'
invalid
'Invalid-Input !'
The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
The regular expression test method is faster than the string search method
You can also test for one or more characters using the + quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
\W being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
You are only testing whether the text ends ($) with one of the characters in the character class. You are also explicitly allowing a dash (\-). If you don't want that, remove it.
Anchor the expression (^, $), add a quantifier (+) and .test whether the string only consists of those characters:
var re = /^[a-zA-Z0-9_]+$/; // or /^\w+$/ as mentioned
if (!re.test(field.value)) {
}
You forgot to anchor your regex at the beginning using ^
test is easier to use
There is no need for the dash.
It should look like this:
if (!/^[a-z0-9_]+$/i.test(field.value)) {
//
}
[\w]* will suffice.
Regex101 Example
This is a very basic Regular Expressions question
Learn more about regular expressions here: regular-expressions.info
In my current regular expression, I am negating digits:
$(function(){
$("#somewhat").bind("keyup",
function(event) {
var regex = /^[\D]*$/;
alert(regex.test($("#somewhat").val()));
});
});
What I have in my mind is to add some special characters on which I should negate, !##$%^&*()_+=<>.?/~`:;" , and leaving dash, apostrophe ( -' ) to the valid list. I'm still kind of dizzy on this regular expression thing. To test with, I added + on the regex,
var regex = /^[\D+]*$/;
When I test it, the alert box returns TRUE, which is not I am expecting.
Inside [ ] please add all the characters you don't want to allow.
/^((?![\d!##$%^&*()_+=<>.?/~`:;"]).)*$/
But can we rely on negating given characters ? because user will be able to enter any character other than these. If you want to allow non-English characters, I would suggest you to use Unicode ranges
see this : http://kourge.net/projects/regexp-unicode-block
[\D+] means "any character that is +, or that is not a digit"; so it's actually equivalent to plain old \D or [\D], since + itself isn't a digit.
To get the meaning of "any character that is neither + nor a digit", you'd have to write [^\d+].
(\D or [\D] is equivalent to [^\d], but its negative-ness doesn't extend beyond that.)