Can someone please tell me how to
add "space" check in email address? I
have tried email.contains("") bt it didnt
worked.
I don't get a error when i type invalid email
import 'dart:async';
class Validators{
final validEmail = StreamTransformer<String, String>.fromHandlers(
handleData: (email, sink){
if(email.contains('#')){
sink.add(email);
}else if(email.contains(" ")){
sink.addError('Enter a valid email');
}else{
sink.addError('Enter a valid email');
}
}
);
final validPassword = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink){
if(password.length > 4){
sink.add(password);
}else{
sink.addError('Enter a valid password');
}
}
);
}
I want "invalid email" error to be displayed as this
Contains works perfectly for me.
void main() {
bool check;
String email = 'tes t#test.com';
check = email.contains(' ');
print(check); // true
}
I have tried it on DartPad
Perhaps you forgot to put whitespace between quotes.
Please don't use hand-rolled regex to validate email addresses. For one, spaces are in fact permitted in email addresses, as long as they are properly quoted, so the original question is already at fault. Also, these regex all reject many perfectly valid email addresses, such as my autoresponder at fred&barney#stonehenge.com. (Go ahead... send it email!)
If you're going to validate email, use https://pub.dev/packages/email_validator, which I have confirmed follows the proper rules.
The error you are having is the order in which you validate the email. You should first check for spaces and then for the # character.
handleData: (email, sink){
if(email.contains(" ")){
sink.addError('Enter a valid email');
} else if(email.contains('#')){
sink.add(email);
} else{
sink.addError('Enter a valid email');
}
}
You can also use a Regular Expression to validate an email address. Although, regular expressions are a bit complex to understand, they are very good for validating strings and checking patterns. Here's an example of a RegEx to validate an email address in Flutter/Dart
// String p to define pattern
String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
//Convert string p to a RegEx
RegExp regExp = new RegExp(p);
//If email address matches pattern
if (regExp.hasMatch(emailAddress)) {
return 'Email is Valid';
}else{ //If it doesn't match
return 'Email is not valid';
}
The simplest solution to this is to call trim() on your email value before passing it. Something like this:
new AuthenticationService()
.signIn(_emailTextController.value.text.trim(),
_passwordTextController.value.text.trim())
Related
I am writing a Flutter/Dart application and am getting a JWT back from an auth server that has some claims I need to use. I have looked at various (4 so far) Dart JWT libraries -- but all are either too old and no longer work with Dart 2, etc. or they need the secret to decode the JWT which makes no sense and isn't correct (or possible since I have no access ).
So -- how can one get a JWT and get the claims from it within a "modern" Dart/Flutter application?
JWT tokens are just base64 encoded JSON strings (3 of them, separated by dots):
import 'dart:convert';
Map<String, dynamic> parseJwt(String token) {
final parts = token.split('.');
if (parts.length != 3) {
throw Exception('invalid token');
}
final payload = _decodeBase64(parts[1]);
final payloadMap = json.decode(payload);
if (payloadMap is! Map<String, dynamic>) {
throw Exception('invalid payload');
}
return payloadMap;
}
String _decodeBase64(String str) {
String output = str.replaceAll('-', '+').replaceAll('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw Exception('Illegal base64url string!"');
}
return utf8.decode(base64Url.decode(output));
}
Use 'base64Url.normalize()' function.
That's what _decodeBase64() does from the answer above!
String getJsonFromJWT(String splittedToken){
String normalizedSource = base64Url.normalize(encodedStr);
return utf8.decode(base64Url.decode(normalizedSource));
}
As of this writing, the jaguar_jwt package is being actively maintained. Although it is not clearly documented, it does have a public method that will decode Base64Url encoding. It does basically the same thing as the accepted answer.
//import 'package:jaguar_jwt/jaguar_jwt.dart';
final String token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTQ4MjAxNjIsImlhdCI6MTU1NDc3Njk2MiwiaXNzIjoiU3VyYWdjaCIsInN1YiI6IjQifQ.bg5B_k9WCmxiu2epuZo_Tpt_KZC4N9ve_2GEdrulcXM';
final parts = token.split('.');
final payload = parts[1];
final String decoded = B64urlEncRfc7515.decodeUtf8(payload);
This gives a JSON string, which for this particular example is:
{
"exp":1554820162,
"iat":1554776962,
"iss":"Suragch",
"sub":"4"
}
See also:
JWT: The Complete Guide to JSON Web Tokens
String based data encoding: Base64 vs Base64url
you can use jwt_decoder package to decode and/or check if you token is expired
//to get claims from your token
main () {
String yourToken = "Your JWT";
Map<String, dynamic> decodedToken =
JwtDecoder.decode(yourToken);
/*
If the token has a valid format, you will get a
Map<String,dynamic> Your decoded token can look like:
{
"sub": "1234567890",
"name": "Gustavo",
"iat": 1516239022,
"exp": 1516239022,
"randomKey": "something else"
}
*/
}
//check if your token is expired
main () {
String yourToken = "Your JWT";
bool hasExpired = JwtDecoder.isExpired(yourToken);
// You will get a true / false response
// true: if the token is already expired
// false: if the token is not expired
}
you can get your token expiration date using
main () {
String yourToken = "Your JWT";
DateTime expirationDate = JwtDecoder.getExpirationDate(token);
// 2025-01-13 13:04:18.000
print(expirationDate);
}
you can also find out how old your token is
// Token payload must include an 'iat' field
main () {
String yourToken = "Your JWT";
Duration tokenTime = JwtDecoder.getTokenTime(token);
// 15
print(tokenTime.inDays);
}
to learn more about what JWT Decoder can do, visit their package documentation page
you can decode JWT base64 by seperate first part of it that contains "."
String decodeUserData(String code) {
String normalizedSource = base64Url.normalize(code.split(".")[1]);
return utf8.decode(base64Url.decode(normalizedSource));
}
I am working on a telegram bot which sends telephone numbers to my telegram account. The problem is, that a '+' is converted to a ' ' blank. So every telephone number is wrong.
E.g. '+4915733000000' turns into '4915733000000'. I've tried to use the HTML code + the unicode version \u002B and the url encoding caracter %2B and none of them work.
https://api.telegram.org/botTOKEN/sendMessage?chat_id=MYID&text=Test:\u2031 Unicode:\u002B HTML:+ URL:%2B
Result: Test:‱ Unicode: HTML:
Do you know any possiblility to send a plus sign?
Thanks!
In case someone is using VBA to send Telegram messages with + in them you can replace your string like that:
Dim URL as String
Dim reURL as String
URL = "https://www.webpage.com/product+name/specifics+number" 'etc....
reURL = replace(URL, "+, "%2B")
'send message to telegram code here
For more Encoding info you can visit: https://www.w3schools.com/tags/ref_urlencode.ASP
It is possible to send the plus sign using POST method.
Here's the sample Google App Script code (can be easily adapted to JavaScript).
var options = {
method : "post",
payload: {
method: "sendMessage",
chat_id: "<chat_id_here>",
text: "+something",
parse_mode: "HTML"
}
};
var response = UrlFetchApp.fetch("https://api.telegram.org/bot<YOUR_TOKEN>/", options);
Plus sign can also be easily sent with parse_mode="Markdown".
Just checked (this time on Python using telebot library) that both options work:
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='Markdown')
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='HTML')
I had the same problem. I was using Java and Spring's WebClient. The only way to make it work is building WebClient using DefaultUriBuilderFactory and set encoding mode to NONE.
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(url);
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
WebClient webClient = WebClient.builder().uriBuilderFactory(factory).filter(logRequest()).build();
Default is EncodingMode.TEMPLATE_AND_VALUES so if you replace + with %2B the resulting URL is %252B. Setting the encoding mode to NONE doesn't replace any especial characters so I had to replace them manually.
private String replaceUrlSpecialCharacters(String message) {
return message.replace("%", "%25").replace("+", "%2B").replace(" ", "%20").replace("|", "%7C").replace(System.lineSeparator(), "%0A");
}
And now the + sign is shown in my messages.
I'am using PHP and this case was solved with rawurlencode. Below is the code:
public function send_message($tg_msg)
{
$tg_token = ''; // Bot Token
$chat_id = ''; // Chat ID
$url = 'https://api.telegram.org/bot' . $tg_token . '/sendMessage?parse_mode=markdown&chat_id=' . $chat_id;
$curlopt_url = $url . '&text=' . rawurlencode($tg_msg);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $curlopt_url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
curl_exec($ch);
curl_close($ch);
}
$msg = 'The message';
send_message($msg);
And now the + sign is shown in my messages.
I got that solved by just using this php function:
utf8_encode(text_to_send)
I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:
A record matching the input was found
Value is required and can't be empty
The input is not a valid email address...
I could write a custom message for every field, but is much effort and copy&paste.
So, I'd like to display the messages like this:
My element Foo label: A record matching the input was found
My element Bar label: Value is required and can't be empty
My element Buz label: The input is not a valid email address...
How to achieve this?
ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by
$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);
and add a method, that process the $messages as desired:
protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
foreach ($messages as $nameOrType => $elementOrError) {
if (is_string($elementOrError)) {
$elementLabel = $element->getLabel()
? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
: null
;
$message = $escapeHtml($elementOrError);
$messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;
} elseif (is_array($elementOrError)) {
$newElement = $element->get($nameOrType);
$this->prepareMessagesToPrint(
$elementOrError, $messagesToPrint, $newElement, $escapeHtml
);
}
}
}
I recently started working on grails and i want to know how to get the
extension of a file. Ex: test.txt. I want to check extension(txt)?
any clue?
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~ to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)
Hope i found the answer of my Question. How to find the extension
of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}
Lsat comment at this post
I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.