I was creating a regular expression in angular to validate password which should have
A number
A uppercase letter
A lowercase letter
Only few symbols i.e !##$%
position of any character or symbol is not restricted.
I have tried this regex
/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/
But the above regex takes any special character to be valid... I just want !##$% this to be valid ele invalid
I'm not sure that all the things you want to do are possible in single regex. But you can use a simple validation function that uses some regex's:
function validate (pass) {
if (
/[A-Z]/.test(pass) && // uppercase letter is required
/[a-z]/.test(pass) && // lowercase letter is required
/[0-9]/.test(pass) && // number is required
/[!##$%]/.test(pass) && // predefined symbol is required
!/[^A-Za-z0-9!##$%]/.test(pass) // there is nothing unwanted
) {
return true;
}
return false;
}
Here is jsfiddle to show that it works.
Try a ng-change listener - something like the following HTML:
<input ng-model="pw" ng-change="checkPwPolicy(pw)">
<div ng-hide="passwordPolicyValid">Your password is too weak!</div>
Combined with this Javascript inside the scope of the controller of this form:
function checkPwPolicy(password) {
var valid = true;
// at least 1 number
valid = valid && password.match(/[0-9]/).length > 0;
// at least 1 uppercase
valid = valid && password.match(/[A-Z]/).length > 0;
// ...
$scope.passwordPolicyValid = valid;
}
Some things you could do to improve this implementation are that you could make the change listener fire less often, hide the error message when the password has not been touched, as well as adding more detailed errors to the password policy message.
Related
I have read few answers online and here on stack overflow but I am not finding a solution.
I am trying to prevent user from copy-pasting invalid characters (anything other than a-z A-Z characters) into my input field. I dont want to do this on submit but on copy-paste event.
If I copy paste text that has all invalid characters (like '1234'), my if block will get executed (regex test fails) and that works fine.
However, it does not work if my copied text contains mix of valid or invalid characters (like '12abc' or 'abc12').
How do I prevent user from copy-pasting text with invalid characters into my input text?
I am calling my javascript function on input text element like this:
function validatePaste(e) {
var regex = /[a-z]/gi;
var copiedText = e.clipboardData.getData('text')
console.log(copiedText,regex.test(copiedText) )
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
References:
Character classes ([...]), Anchors (^ and $), Repetition (+, *)
The / are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
function validatePaste(e) {
var regex = /^[a-zA-Z]*$/;
var copiedText = e.clipboardData.getData('text')
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
You only test there is one char there
Here is a better regex - also we do not need to assign it every time
const regex = /^[a-z]+$/gi; // gi makes A-Z irrelevant
function validatePaste(e) {
const copiedText = e.clipboardData.getData('text')
console.log(copiedText, regex.test(copiedText))
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes if copiedText has any invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
In my application someone can submit text from another language. I'd like for only English alphanumeric strings to be entered. I've got this JavaScript function working but wondering if this is the best method for doing this?
var string = $('input[name=title]').val();
if((/\d/.test(string) || /[a-zA-Z]/.test(string)) === false) {
alert('Field has no Alphanumeric characters.');
fPass = false;
}
Even if some just enters 1 character I want that to be allowed, as long as it is a number or a character from one of the 26 letters in the English alphabet (case insensitive)
Without using a function here is what I've come up with
if((/[\da-z]/i.test(string)) === false) {
alert('Please use alphanumeric characters.')
}
You can combine your regex into one expression.
function hasAlphanumeric(str) {
return /\d|[A-z]/.test(str)
}
You can use
^[\da-z]+$
let allowAlphanumeric = (str) =>{
return /^[\da-z]+$/i.test(str)
}
console.log(allowAlphanumeric('$##'))
console.log(allowAlphanumeric(''))
console.log(allowAlphanumeric(' '))
console.log(allowAlphanumeric('abchbchdb12e44'))
im having some issues concerning my javascript code for password. here's my code .that part is working fine, but i want to put another condition where my password should contains at least 8 characters and must abide the following rules : no spaces, contains at least 1 Uppercase and a number. concerning the mobile, it must always start with the no. 5 . help <3
function formValidation() {
var mobile = document.forms["form"]["mobile"].value;
var password = document.forms["form"]["password"].value;
//reg expression check
var checkNumbers = /^[0-9 ]+$/;
$(document.forms["form"]["mobile"]).focus(function(){
$(document.forms["form"]["mobile"]).css("background-color", "white");
});
$(document.forms["form"]["password"]).focus(function(){
$(document.forms["form"]["password"]).css("background-color", "white");
function clear(){
$(document.forms["form"]["mobile"]).focus(function(){
$(document.forms["form"]["mobile"]).css("background-color", "white");
});
$(document.forms["form"]["password"]).focus(function(){
$(document.forms["form"]["password"]).css("background-color", "white");
});
}
if (mobile == null || mobile == "") {
error[error.length]=("Enter your mobile number");
document.form.mobile.focus();
$(document.forms["form"]["mobile"]).css("background-color", "blue");
;
}else if (mobile != null || mobile != "") {
if(!checkNumbers.test(mobile)){
error[error.length]=("Enter Only numeric Characters for mobile phone");
document.form.mobile.focus();
$(document.forms["form"]["mobile"]).css("background-color", "blue");
}
}
if (password == null || password == "") {
error[error.length]=("Enter a password");
document.form.password.focus();
$(document.forms["form"]["password"]).css("background-color", "blue");
}
}
<form name="form" onsubmit="return formValidation()" action="process.html">
Mobile phone:
<input type="text" name="mobile" id="mobile"></br></br>
Password:
<input type="password" name="password" id="password"></br></br>
</form>
<input id="submit" type="submit" name="submit" id="submit">
If you break it down into parts you can do this really easily and inform the user exactly which constraint they are failing, like this:
// Check the length:
if (password.length < 8) { // ... not long enough }
// Check if it has at least one upper case:
if (password.match(/[A-Z]+/g) === null) { // ... no upper case characters }
// Check if it has at least one number:
if (password.match(/\d/g) === null) { // ... no numbers }
// Password passes validation!
Test if all your conditions are met (c1 condition 1 and so on)
var c1 = (password.toLowerCase() != password);// if it HAS uppercase letters, it won't match
var c2 = password.length > 8;
var c3 = !(password.indexOf(" ") > -1); // no spaces
var c4 = password.match(/\d+/g); // matches numbers
You can create a RegExp object and then pass in your password to its test method. The RegExp object can use positive lookaheads to assert that it finds an uppercase character and a digit character.
Finally, you can test that the password is at least 8 characters long and contains no white-space characters by attempting to pattern match at least 8 non-whitespace characters between the beginning-of-string token (^) and the end-of-string token ($). The pattern match will consume the entire string so if any whitespace characters are found, the test will fail, and if there are less than 8 characters, the test will also fail.
/(?=.*[A-Z])(?=.*\d)^\S{8,}$/.test(password)
^uppercase ^digit ^8+ characters in length and no whitespace
This expression will evaluate to true if the password is okay and false if not.
I have textbox called goalName. In goalName I want to disallow special characters and numbers. I am currently trying the following:
var goalNameValidation = /^[_\W\s]*$/;
if (goalName == "" || goalNameValidation.test(goalName) == true) {
//Give Error
error = true;
}
This only limits special characters, and not numbers. How would I go about restricting both?
I can use jQuery for this solution if that is helpful, however vanilla JavaScript would suffice.
It is probably easier (and more intuitive) to write a regex that matches what you WANT to allow.
var goalNameValidation = /^[A-Za-z]+$/;
if (goalName == "" || goalNameValidation.test(goalName) == false) {
//Give Error
error = true;
}
This way, you can look at it, and see more easily what characters are allowed/not allowed.
Change the regexp to:
var goalNameValidation = /^[^a-z]*$/i;
I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.
Now the problem is it gives the following result:
r = /[\u0600-\u06FF]/
r.test("abcd") // false - correct
r.test("##$%^") // false - correct
r.test("س") // true - correct
r.test("abcd$$#5س") // true - should be false
r.test("abcdس") // true - should be false
If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?
You need to add ^ and $ anchors to the regular expression, as well as a + to allow multiple characters.
Try this:
/^[\u0600-\u06FF]+$/
I'm not sure if "Arabic spaces" that you mentioned are included in the character range there, but if you want to allow white space in the string then just add a \s inside the [] brackets.
You can explicitly allow some keys e-g: numpad, backspace and space, please check the code snippet below:
function restrictInputOtherThanArabic($field)
{
// Arabic characters fall in the Unicode range 0600 - 06FF
var arabicCharUnicodeRange = /[\u0600-\u06FF]/;
$field.bind("keypress", function(event)
{
var key = event.which;
// 0 = numpad
// 8 = backspace
// 32 = space
if (key==8 || key==0 || key === 32)
{
return true;
}
var str = String.fromCharCode(key);
if ( arabicCharUnicodeRange.test(str) )
{
return true;
}
return false;
});
}
// call this function on a field
restrictInputOtherThanArabic($('#firstnameAr'));