how to modify a String from a Textfield before validated using validator? - flutter

I am using form field validator, I think it will be the same if using normal TextField, and I have form field like this
TextFormField(
onChanged: (val) => selectedEmail = val,
validator: EmailValidator(errorText: "Email is not valid"),
)
unfortunately, my user sometimes unintentionally will put an empty string at the end of email string like this :
"john#gmail.com "
as you can see, I have email validator here, but the email validator will consider the string with empty space like that as an invalid email.
I want to remove or trim the email string first before it is validated by the EmailValidator, how to do that?

TextFormField(
onChanged: (val) => selectedEmail = val,
validator: EmailValidator(errorText: "Email is not valid"),
inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))]
)
FilteringTextInputFormatter.deny(RegExp(r'\s')) it's deny white space in the TextFormField

It could be helpful.
TextFormField(
onChanged: (val) => selectedEmail.trim() = val.trim(),
validator: EmailValidator(errorText: "Email is not valid"),
)

Related

I m trying to fetch order details from website and getting error "A non-null String must be provided to a Text widget'

1.getting error on this line as null
enter code here
return OrderItem(
order: model.myOrders[index],
onRefresh: refreshMyOrders,
);
}),
),
)
You have to check if the indexed order is null and set a default value to protect your code from these types of errors like this:
return OrderItem(
order: model.myOrders[index] ?? 'Default Value',
onRefresh: refreshMyOrders,
);
}),
),
)

Yup validation check if not empty

const validationSchema = Yup.object().shape({
newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});
I want to validation check only if newPassword field is not empty.
How could I do?
There are different approach on solving this problem.
Using test
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-check',
'Password must be at least 8 characters',
password => password.length == 0
});
Using when
const validationSchema = Yup.object().shape({
newPassword: Yup.string().when('newPassword',{
is:(password) => password.length > 0
then: Yup.string().min(8, 'Password must be at least 8 characters');
});
Alternative using test:
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-or-8-characters-check',
'Password must be at least 8 characters',
password => !password || password.length >= 8,
),
});
Alternative using trim()
const validationSchema = Yup.object().shape({
newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
});
There is a way of using .when() and not generating a cyclic dependency like the accepted answer, .shape() accepts an exhaustive list of dependencies as last argument, that resolves the cyclic conflict, the secret is using the same key twice https://github.com/jquense/yup/issues/176#issuecomment-369925782
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-or-8-characters-check',
'Password must be at least 8 characters',
password => !password || password.length >= 8,
),
}, [["newPassword","newPassword"]]);
The way I solved this for myself was to first add .nullable() and then .transform() empty string into a null.
const validationSchema = Yup.object().shape({
newPassword: Yup
.string()
.nullable()
.transform((v, o) => (o === '' ? null : v))
.min(8, 'Password must be at least 8 characters')
});
The simplest way is:
const validationSchema = Yup.object().shape({
newPassword: Yup
.string()
.matches(/^\w{8}/, "Password must be at least 8 characters")
});
Alternative that won't allow 8 empty characters.
const notEmpty = Yup.string()
.ensure() // Transforms undefined and null values to an empty string.
.test('Only Empty?', 'Cannot be only empty characters', (value) => {
const isValid = value.split(' ').join('').length !== 0;
return isValid;
});
const validationSchema = Yup.object({
newPassword: notEmpty.min(8, 'Password must be at least 8 characters');
});
I used the Yup function nullable() so it is only validated with the next functions if it not null:
kmBegin: Yup.number().nullable().positive().integer(),
parcelTotal: Yup.number().positive().integer(),
timeBegin: Yup.date(),
timeEnd: Yup.date().nullable(),

Validate default values

I have a form which consists of selects/dropdowns. I have set their default values to be -1. When the form is submitted, I want to validate that the submitted value is not equal to the default value. I tried setRequired(true), but as far as I know, that is just a convenient way of adding a notEmpty validator, which is not really what I want.
Here is a part of my form:
$select = new Zend_Form_Element_Select('myselect');
$select->setMultiOptions(array(
'-1' => 'Gender',
'0' => 'Female',
'1' => 'Male'
))
->addValidator(new Zend_Validate_Int(), false);
$this->setDefaults(array('myselect' => -1));
And here is my controller:
if ($this->getRequest()->isPost()) {
$form = new My_Form_Contact();
if ($form->isValidPartial(array('myselect' => $this->getRequest()->getPost('myselect')))) {
// "myselect" is valid
}
I need to use the isValidPartial method because I need to use different logic depending on which elements have a value that is different from their default value. I guess what I need is a notEqual validator, but I couldn't find one. I know that it is possible to make my own validators, but I wanted to ask if there is an easier way first. I also looked at Zend_Validate_Identical, but I don't think I can make use of it in this case.
To sum up: I only want my select to be validated successfully if the submitted value is not equal to the default value.
The simplest solution is to use an empty string as the default:
$select->setMultiOptions(array(
'' => 'Gender',
'0' => 'Female',
'1' => 'Male'
))
->addValidator(new Zend_Validate_Int(), false)
->addValidator(new Zend_Validate_NotEmpty(), false);
$this->setDefaults(array('myselect' => ''));
but I'm guessing you already thought of that, and discounted it from some reason.
So, the next easiest is to use GreaterThan():
$select->setMultiOptions(array(
'-1' => 'Gender',
'0' => 'Female',
'1' => 'Male'
))
->addValidator(new Zend_Validate_Int(), false)
->addValidator(new Zend_Validate_GreaterThan(-1), false);
$this->setDefaults(array('myselect' => '-1'));
I hope that is what you are looking for.

zend form email validation

I have the following code to generate an input field for user's email address
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress')
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
)))
->setRequired(true)
->setDecorators(array(
array('Label', array('escape'=>false, 'placement'=>'append')),
array('ViewHelper'),
array('Errors'),
array('Description',array('escape'=>false,'tag'=>'div')),
array('HtmlTag', array('tag' => 'div')),
));
$this->addElement($email);
now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin#l' as email address, and the errors will be
* 'l' is no valid hostname for email address 'admin#l'
* 'l' does not match the expected structure for a DNS hostname
* 'l' appears to be a local network name but local network names are not allowed
I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.
Well, it's a late answer but I think is always useful.
Simply add true as second param of addValidator()
From Zend docs (http://framework.zend.com/apidoc/1.8/):
addValidator (line 67)
Adds a validator to the end of the chain
If $breakChainOnFailure is true, then if the validator fails, the next
validator in the chain, if one exists, will not be executed.
return: Provides a fluent interface
access: public
Here the signature:
Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])
Zend_Validate_Interface $validator
boolean $breakChainOnFailure
So the code is:
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress', TRUE ) // added true here
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
), TRUE )
);
You have to create an instance of the Zend_Validate_EmailAddress class and call the setMessages method and then override the messages that you like, to remove the ones that you mention it would be something like this:
$emailValidator->setMessages(array(
Zend_Validate_EmailAddress::INVALID_FORMAT => "Your error message",
Zend_Validate_Hostname::INVALID_HOSTNAME => "Your error message",
Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED => "Your error message"
));
I hope this help somebody :-)
$email->addErrorMessage("Please Enter Valid Email Address");
you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project
class Validate_Email extends Zend_Validate_Abstract
{
const INVALID = 'Email is required';
protected $_messageTemplates = array(
self::INVALID => "Invalid Email Address",
self::ALREADYUSED => "Email is already registered"
);
public function isValid($value)
{
if(preg_match($email_regex, trim($value))){
$dataModel = new Application_Model_Data(); //check if the email exists
if(!$dataModel->email_exists($value)){
return true;
}
else{
$this->_error(self::ALREADYUSED);
return false;
}
}
else
{
$this->_error(self::INVALID);
return false;
}
}
}
and in you form.php file
$mailValidator = new Validate_Email();
$email->addValidator($mailValidator, true);
Don't know if it works or not but for me it worked in case of telephone. Courtesy of http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/
It seems to be missing quite a few lines...
probably should use this:
$mailValidator = new Zend_Validate_EmailAddress();
you can also do some other validations see here: http://framework.zend.com/manual/en/zend.validate.set.html
Using a custom validator is the only way I found to avoid this problem.
If what you want is:
Having only one error message if the email address is in a wrong format
If the format is good, then validate if the email address is already in the database
Then I suggest you to do something like this:
$where = array('users', 'email', array('field' => 'user_id',
'value' => $this->getAttrib('user_id')));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail:')
->setRequired(true)
->setAttrib('required name', 'email') // html5
->setAttrib('maxlength', '50')
->addFilter('StripTags')
->addFilter('StringTrim')
->addFilter('StringToLower')
->addValidator('email', true)
->addValidator('stringLength', true, array(1, 50))
->addValidator('db_NoRecordExists', true, $where)
->addDecorators($this->_elementDecorators);
$this->addElement($email);
$this->getAttrib('user_id') represents the current user's id.
There are three validators here, all of them have their second parameter $breakOnFailureset to false, so if a validator fails, the other ones won't be called.
The first validator is email, which is my own custom validator:
class My_Validate_Email extends Zend_Validate_EmailAddress
{
public function getMessages()
{
return array('invalidEmail' => 'Your email address is not valid.');
}
}
You can add this validator in your library, in /application/library/My/Validate for example, and then add
$this->addElementPrefixPath('My_Validate', 'My/Validate', 'validator');
into your form. Of course, you need to replace "My" by the name of your library.
Now if an email is in the wrong format, it will always display 'Your email address is not valid.'. If your email is too long and doesn't fit into your database field (VARCHAR(100) for example), it's going to show your stringLength validator errors, and in the last case, if an entry already exists in the database, only this error will be shown.
Of course you can add more methods into your custom validator and overload setMessages, so that you can display your own messages whatever the form you are working on.
Hope it can help someone!

Problem with Symfony form validation

I'm unable to see what I may be doing wrong with the following Symfony 1.4 form validation. Basically, all I just want is for all four conditions to be taken correctly into account (required, min-length, max-length, regular expression). It actually WORKS, but for the 'required' condition it fails to display my custom error message and just says "Required" instead. Is there a way to get MY error message to show?
'username' => new sfValidatorAnd(array(
new sfValidatorString(
array('required' => true, 'min_length' => 4, 'max_length' => 20),
array('required' => 'Please enter a username.', 'min_length' => 'Your username must have at least 4 characters.', 'max_length' => 'Your username cannot be longer than 20 characters.')
),
new sfValidatorRegex(
array('pattern' => '/^[A-z0-9]*$/i'),
array('invalid' => 'Your username can only have letters (A-Z) or numbers (0-9).')
),
)),
One additional thing, if I remove the Regex validator and just turn it into a normal single-line String validator, my custom error message does show!?
Anyone?
Thanks in advance.
I've noticed same issue about two weeks ago and found a solution - just move your message to sfValidatorAnd declaration:
'username' => new sfValidatorAnd(array(
new sfValidatorString(
array('required' => true, 'min_length' => 4, 'max_length' => 20),
array( 'min_length' => 'Your username must have at least 4 characters.', 'max_length' => 'Your username cannot be longer than 20 characters.')
),
new sfValidatorRegex(
array('pattern' => '/^[A-z0-9]*$/i'),
array('invalid' => 'Your username can only have letters (A-Z) or numbers (0-9).')
),
), array(), array('required' => 'Please enter a username.')),
That helped me, I hope it helps you too.