Write a program to take a password as an input from the user. The
password must qualify these requirements:
a. It should contain alphabets and numbers
b. It should not start with a number
c. It must at least 8 characters long
d. If the password does not meet the above requirements, prompt
the user to enter a valid password. For character codes of a-z,
A-Z & 0-9
I'm using the following code. Don't know why the pattern is always false.
const pattern = /([a - zA - Z][a - zA - Z0 - 9]{ 8, })/;
const userInput = prompt('Enter Password');
console.log(pattern.test(userInput));
// while (!pattern.test(userInput)) {
// prompt("Please Enter valid password")
// }
alert('Correct password');
Here is the solution
const pattern = /^[0-9a-zA-Z]+$/;
const patternTwo = /^[0-9]+$/;
let userInput;
do {
userInput = prompt("Please Enter valid password");
} while (!pattern.test(userInput) || userInput.length < 8 || patternTwo.test(userInput[0]));
alert('Correct password');
Related
In the code below, we have a method which is called whenever the user clicks on the 'Sign Up' button (on our Authentication screen). Currently this method has two different conditions, if it doesn't pass these conditions, the user won't be able to sign up.
We'd also like to add one more condition here. We have an array of strings that shouldn't be accepted as usernames (bad words). But if the bad word is used in combination with other letters or numbers, it should also not be accepted.
Example of a "bad word": Charlie
That means Charlie shouldn't be accepted as a username but there's also potential for millions of other combinations, examples: Charlieee, Charlie124342, Charlie6648, 213charlie, ch1chaRliE32, etc. etc.
So would there be any simple method to check whether the username entered contains any of the bad words listed in an array, regardless of whether its used in combination with other characters or not?
Future<String?> usernameValidator({required String? username}) async {
// Validates username complexity
bool isUsernameComplex(String? text) {
final String _text = (text ?? "");
String? p = r"^(?=(.*[ #$!%*?&=_+/#^.~`]))";
RegExp regExp = RegExp(p);
return regExp.hasMatch(_text);
}
final String _text = (username ?? "");
// Complexity check
if (isUsernameComplex(_text)) {
return "Username can only contain letters and numbers.";
}
// Length check
else if (_text.length < 3 || _text.length > 16) {
return "Username must be between 3-16 characters long.";
}
return null;
}
see if this helps:
List<String> badwords = [
'charlie',
'another_badword',
];
List<String> input = [
'Charlieee',
'Charlie124342',
'Charlie6648',
'213charlie',
'ch1chaRliE32',
'spaghetti',
];
input.forEach((text) {
final bwIndex = badwords.indexWhere(
(badword) => text.toLowerCase().contains(badword),
);
if (bwIndex != -1) {
print('$text is bad word, similar to ${badwords[bwIndex]}');
} else {
print('$text is not a bad word');
}
});
In my form validation I already added stuff like the username already exists or it should be longer than n letters etc. but now I want to add more restrictions and display a message that says 'username' is invalid when it's not in English or if it has stuff like underscores slashes etc. is there a way for me to do that?
For just the English Alphabets you need to set a regex for the alphabetical pattern checking. Create a static final field for the RegExp to avoid creating a new instance every time a value is checked.
static final RegExp alphaExp = RegExp('[a-zA-Z]');
And then to use it :
validator: (value) => value.isEmpty
? 'Enter Your Name'
: (alphaExp.hasMatch(value)
? null
: 'Only Alphabets are allowed in a username');
you can set textfields validations like this it will only except characters a to z. and add validation in textfield through this
class FormValidator {
static String validateEmail(String? name) {
if (name!.isEmpty) {
return 'Name is must not e empty';
}
String pattern =
'([a-zA-Z])';
RegExp regExp = RegExp(pattern);
if (!regExp.hasMatch(name)) {
return 'invalid name';
}
return '';
}
}
I am making a register form that can check whether there is or not in the database and how to validate the username must use alphanumeric and no spaces,
this is my code for now
String validateUsername(String value) {
String pattern = r'^(([^<>()[\]\\.,;:\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,}))$';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return "Username is Required";
} else if(!regExp.hasMatch(value)){
return "Invalid username";
}else {
return null;
}
}
I think the validation is almost the same as email, but I'm still confused
This is how I do it.
while using flutter.
// import needed for BlackListingTextInputFormatter function
import 'package:flutter/services.dart';
TextField(
inputFormatters: [
BlacklistingTextInputFormatter(
new RegExp("[^a-z^A-Z^0-9]+")) //Regex for accepting only alphanumeric characters
],
)
using this it will ensure no character other than alphanumeric can pass through the textfield.
so now you just need to check the string you get from that field with the database.
You can make an api and make an query like
SELECT * FROM user WHERE user_name = "userName";
if you get an empty response then that username is available.
I have a string and say I want to check the last 3 digits of the string for some range.
if the string is like sasdaX01, I need to check the last three digits of the string are between X01-X50.
ANy help would be highly appreciated.
The use spl.string::*; line is mandatory and then you extract your last digits with substring(info, length(info) - 3, 3).
An example:
use spl.string::*;
composite TestComposite {
graph
// ... code generating (stream<rstring info> testStream)
() as PrintTestInfo = Custom(testStream as infoEvents) {
logic
onTuple infoEvents : {
rstring lastDigits = substring(info, length(info) - 3, 3);
boolean matched = (lastDigits >= "X01" && lastDigits <= "X50");
println(info + " matched > " + (rstring)matched) ;
} // onTuple infoEvents
} // PrintTestInfo
} // TestComposite
Hi i used a basic captcha script as below . The problem i am facing is that , inspite of wrong captcha value, the form is submitted . I need to prevent the form from submission if the value of Captcha is entered wrong .
<?php
if(isset($_POST['submit']))
{
$hash = (!empty($_POST['hash'])) ? preg_replace('/[\W]/i', '', trim($_POST['hash'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
$captchacode = (!empty($_POST['captchacode'])) ? preg_replace('/[\W]/i', '', trim($_POST['captchacode'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
// function to check the submitted captcha
function captchaChars($hash)
{
// Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
// Adding the servers name means outside sources cannot just work out the characters from the hash
$captchastr = strtolower(md5($_SERVER['SERVER_NAME'] . $hash));
$captchastr2 = '';
for($i = 0; $i <= 28; $i += 7)
{
$captchastr2 .= $captchastr[$i];
}
return $captchastr2;
}
if(!empty($captchacode))
{
if(strtolower($captchacode) == captchaChars($hash)) // We convert submitted characters to lower case then compare with the expected answer
{
echo '<h3>The submitted characters were correct</h3>';
}
else
{
echo '<h3>The submitted characters were WRONG!</h3>';
return true;
}
}
else
{
echo '<h3>You forgot to fill in the code!</h3>';
return true;
}
}
?>
I had Captcha up and running on my website and it did nothing to prevent spam. It has been compromised as a spam prevention mechanism I'm afraid.
Besides that, you need to return false if the captcha is incorrect and the form will not be submitted.