is there a way to validate if a users input is a valid float?
I need to verify that the user is inputting valid project estimates $$
only costs up to the hundreds is allowed, example:
1.99
.99
no commas are allowed
no negative numbers
only one period is allowed
I am using a TextFormField, and I am using the following keyboard:
keyboardType: TextInputType.number,
I know I have to do some type of validation using the validator but I am stuck
validator: (str) {
if (str == '' || str == '.') {
return "Job estimate can't be empty";
}
if (str!.contains(',')) {
return 'No commas are allowed';
}
var strPlit = str.split('.');
print('strPlit: ${strPlit.length}');
if (strPlit.length != 1) {
if (strPlit.length > 2) {
return 'Only 1 period allowed';
}
if (strPlit[1].length > 2) {
return 'Estimate is only accurate to the hundreds';
}
}
return null;
},
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');
}
});
I am trying to check value using if but the app crash on that line. I am using flutter.
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
getting that
Error: Property 'isEmpty' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.
Please update Flutter and Dart to the latest versions. The error you describe should not happen.
This example is compiling and running perfectly fine, printing:
Please enter a valid email.
null
With no warnings or errors.
String? isValid(String? value) {
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
return null;
}
void main() {
print(isValid(null));
print(isValid('valid#email.example.com'));
}
Replace
value.isEmpty
With
(value.toString()).isEmpty
Do this instead
if((value != null && (value.isEmpty() ||
!value.contains('#'))) || (value ==
null)){
}
If you have declared a variable to be nullable and did not assign a default value, and later you want to use isEmpty on that variable, you must first check that the variable is not null before checking if it's empty or not.
Adding my comment as answer so you can have better view of it:
if (value == null || ( value?.isEmpty ?? true ) || (!value?.contains('#') ?? true )) {
return 'Please enter a valid email.';
}
YOU HAVE TO REPLACE SOME OF YOUR CODE
value.isEmpty
REPLACE IT WITH
( value?.isEmpty ?? true )
I want to validate a TexFormField field to both check for a min value of 10 (done elsewhere) and also check that the value entered is a multiple of 10.
I've written a function that tries to handle both and it seems to work. However, it feels clunky. And it doesn't provide any feedback until the form is submitted. Here is what I've written:
final form = _formKey.currentState;
if ((form.validate()) && (_amount / 10 is int)) {
form.save();
return true;
}
return false;
}
Is there a cleaner way to check if an entered value is a multiple of 10 (or any integer)? For example, in the validator: property field itself?
validator: (String value) {
int n = int.parse(value);
int multipleOf = 10;
return n % multipleOf != 0 ? "not a multiple of $multipleOf" : null;
}
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.
function getCode() {
if (window.location.href.indexOf("?discount=")) {
var url = (document.URL);
var id = url.substring(url.lastIndexOf('=') + 1);
window.alert(id);
return true;
} else {
return false;
}
}
Purpose: When people go to our "Service Request" page using a QR code that has a substring of ?discount=1234. I have been testing by creating an alert box with the discount code showing. Eventually I want to be able to populate that "1234" automatically into a "Discount Code:" text field on page load.
The above is a mixture of a few suggestions when I researched it.
Result: Going to example.com/serviceRequest.html?discount=1234 gives me the appropriate alert "1234", as I want... Going to example.com/serviceRequest.html gives me the alert http://example.com/serviceRequest.html, but I don't want anything to happen if "?discount=" is null.
Any suggestions?
indexOf returns -1 if the search pattern doesn't exist. In JavaScript, anything not a 0 or false or undefined is considered true.
So your line of:
if(window.location.href.indexOf("?discount=")) {
Would better search as:
if(window.location.href.indexOf("?discount=") > -1) {
Try changing your if-statement to:
if(window.location.href.indexOf("?discount=") != -1)
Look up the documentation for ".indexOf". It returns -1 for not found and >= 0 if it is found.
...indexOf("?discount=") >= 0
substring and indexOf return -1 if the text is not found, so you can test for this. E.g.
function getCode() {
if(window.location.href.indexOf("?discount=") != -1) {
var url = (document.URL);
var id = url.substring(url.lastIndexOf('=') + 1);
window.alert(id);
return true;
}
else {
return false;
}
}
You just need to test the indexOf value:
function getCode() {
if (window.location.href.indexOf("?discount=") !== -1) {
var url = (document.URL);
var id = url.substring(url.lastIndexOf('=') + 1);
window.alert(id);
return true;
}
else {
return false;
}
}
So the quick and dirty answer would be
var discount = window.location.search.split("?discount=")[1];
alert(discount);
But this doesn't take into account the occurence of other query string parameters.
You'll really want to parse all the query parameters into a hash map.
This article does a good job of showing you a native and jQuery version.
http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html