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 '';
}
}
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');
}
});
Results in my react table should be like this:
"/.\u0010\u0016u/LGIRLGAV0735017500099A925",
but the result looks like this:
"/.■■u/LGIRLGAV0735017500099A925".
Black squares are actualy empty (only borders).
How to avoid the backslash character being displayed as an empty square?
Also, everithing in between backslashes missing.
Thank you in advance!
\ character followed with some other characters represents JS escape character. In my case \ was followed with u0012 (ie. \u0012). That was presented as: .■.
I was solve the problem in columns.js (subcomponent of React-Table) with JSON.stringify() method. This is most important for this problem, other
is just formating of my print.
// replace null result with '' function replacer(key, value) { // Filtering out properties if (value === null) { return ''; } return value; } export const COLUMNS = [ { Header: "Text", accessor: "text", Cell: ({ value }) => { return JSON.stringify(value, replacer, '').replace(/"/g, '').split("").join(" ")}, },
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');
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.
This is function which is I'm using at liveChange event:
if (oEvent.mParameters.value.indexOf(" ") === 0) {
sap.m.MessageToast.show("Space character is not allowed");
oEvent.preventDefault();
return false;
}
By using this code I have to restrict the whitespaces at the beginning in the input field. I tried a lot, I'm getting the message but it is taking the whitespace. How can I make an input field display only message and it should not take whitespaces.
To "invasively" remove the whitespace in the beginning of the input, you can do something like this:
onLiveChange = function(oEvent) {
var sValue = oEvent.getParameter('value');
if (sValue[0] === ' ') { // or use sValue.match(/^ /)
oEvent.getSource().setValue(sValue.trimStart());
sap.m.MessageToast.show("Space character is not allowed");
}
}
Also have a look at this SAPUI5 Demokit Sample as well as the validationError and validationSuccess events of class `sap.ui.core.Core' to get an idea of the recommended way of handling validation.