How do I use the 'When' method in ASP.NET MVC Fluent Validation? - asp.net-mvc

I am trying to develop a fluent valiation rule where if my TitleId FK property is null, then the TitleOther text field becomes mandatory. I have tried several combinations and orders of fluent expressions, all to no avail.
This is what I have so far, if someone can please help me get this one When part correct, I would be most grateful, and a little more educated.
context.RulesFor(p => p.TitleId).Required(p => p.Message("Title is required."));
context.RulesFor(p => p.TitleOther)
.Required(p => p.Message("Please provide your other title."))
.Length(0, 50, c => c.Message("Other title may not exceed 50 characters")
.When(p => context.RulesFor(p => p.TitleId). *[what here?]*

I haven't used FluentValidation much, but from what I understand from the docs you would need to do
.When(p => p.TitleId == null)
instead of .When(p => context.RulesFor(p => p.TitleId). *[what here?]*

I have used When in my project in Fluent Validation. I have used for 1 condition that is compare password as like below:
RuleFor(u => u.Password).NotEmpty().WithMessage("Please Enter Password"); // Normal checked for non empty
When(u => !string.IsNullOrEmpty(u.Password) && !string.IsNullOrEmpty(u.ComfirmPassword), () =>
{
RuleFor(u => u.ComfirmPassword).Equal(x => x.Password).WithMessage("Password does not match");
}); // For compare password
Hope it helps you.
Thanks.

Related

Breezejs clear multple keys

We have the following mapping in EF6:
HasRequired(x => x.modulemain).WithMany().HasForeignKey(t => t.moduleid);
HasOptional(t => t.modulerslt).WithMany().HasForeignKey(t => new { t.moduleid, t.trmendrs });
HasOptional(x => x.modulegoal).WithMany().HasForeignKey(t => new { t.moduleid, t.trmgcode });
HasOptional(x => x.modulefase).WithMany().HasForeignKey(t => new { t.moduleid, t.trmfcode });
Breezejs understands this mapping with the combination of the two keys. BUT there is a problem: Whenever the user 'clears (sets its value to NULL)' the modulegoal/modulefase/modulerslt sets the moduleid value to an empty string and the 'second key' as well. The problem is that the first keys is being used in multiple references. So clearing one of the references, mismatches the other (important) references. Is there any way to tell breeze to NOT clear the first key?

EntityFramework - Port WithRequired to EF Core

I'm porting an application from MVC5/EF6 to MVC6/EF7, but having an issue with this particular line:
modelBuilder.Entity<Client>().HasMany(c => c.Payments).WithRequired(e => e.Client).WillCascadeOnDelete(false);
Apparently the WillCascadeOnDelete is transformed to the OnDelete with restrict as parameter, but I can't find any documentation on the "WithRequired" part which has disappeared too in EF7. Has 'WithOne' the same impact or am I completely wrong here :
modelBuilder.Entity<Client>().HasMany(c => c.Payments).WithOne(e => e.Client).OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
You are correct in both cases. Here is a detailed post... http://www.mikee.se/posts/migrating_from_ef6_to_ef_core
Typically these mappings would change from this in EF6.
x.Entity<Company>()
.HasMany(c => c.StatementOfEarnings)
.WithRequired(e => e.Company)
.WillCascadeOnDelete(false);
To this in EF Core
x.Entity<Company>()
.HasMany(c => c.StatementOfEarnings)
.WithOne(e => e.Company)
.OnDelete(DeleteBehavior.Restrict);

Mvc CheckBoxListFor named argument specifications error

Im using Mvc CheckBoxListFor extension. Argument specification seems quite right to me as it's shown on the demos but it still gives me named argument specifications must appear after all fixed arguments have been specified error. And i also want to specify id attribute.
Thanks for any help in advance.
#Html.CheckBoxListFor(model => model.Categories.PostedCategories.CategoryIds,
model => model.Categories.AvailableCategories,
entity => entity.CategoryId,
entity => entity.Name,
model => model.Categories.SelectedCategories,
position: Position.Horizontal,
x => new { #class = "actcheckbox" }) // here is the line that occurs that error.
#Html.ValidationMessage("catSelectionError")
As the error message suggests, you have a named argument which is followed by a fixed argument - position: Position.Horizontal. It would seem you need to do the following:
#Html.CheckBoxListFor(model => model.Categories.PostedCategories.CategoryIds,
model => model.Categories.AvailableCategories,
entity => entity.CategoryId,
entity => entity.Name,
model => model.Categories.SelectedCategories,
Position.Horizontal, // NB: No argument name
x => new { #class = "actcheckbox", id = "myid" }) // Add id here

Symfony form values do not bind

I am using Symfony 1.4 forms for a simple login module. The form, pretty basic has it's code listed below:
<?php
class LoginForm extends sfFormSymfony
{
public function configure()
{
$this->setWidgets(
array('username' => new sfWidgetFormInputText(),
'password' => new sfWidgetFormInputPassword(),));
// 'remember_me' => new sfWidgetFormSelectCheckbox(array('choices'=>array('true'=>''))),));
$this->widgetSchema->setNameFormat('login[%s]');
$this->setValidators(array(
'username' => new sfValidatorString(array('required'=>true)),
'password' => new sfValidatorString(array('required'=>true)),
));
}
}
The form renders fine in the template page as expected. FYI, I use $form['username']->render method to individually render the methods where I like them instead of echoing the form out.
Upon post (recognized) I bind values to the form like this:
$this->form->bind($request->getParameter('login'));
However, it fails against the condition
$this->form->isValid();
Both the fields are not being left empty and the credentials are correct, so this seems something more insidious to me.
Upon doing a var_dump($this->form->getValues()); it returns an empty array which I believe implies that the values were not retrieve nor bound.
Can anybody spot where I possibly am messing up ?
Thanks
As of symfony 1.3, csrf protection is enabled by default. This means that all your forms get a csrf token field, named _csrf_token by default - it's a hidden field that's unique to your session and the given form type.
If you don't render and submit this field with the rest of your form it will be invalid - it detects a csrf attack, so it's good this way.
The short fix is to render the token field:
echo $form["_csrf_token"]->render();
But the better way is to render all hidden fields in one go (I usually did this next to the submit button):
echo $form->renderHiddenFields();
If you really need to, you can use a little snippet to display errors like this:
foreach ($this->getErrorSchema() as $field => $error) {
if ($error instanceof sfValidatorErrorSchema) {
foreach ($error as $field => $error) break;
}
echo $field . ' => ' . $error; // e.g. "Field name" => "Error message".
}
#Maerlyn resolved this. For future reference:
The form fields were being rendered individually instead of using vanilla echo $form. Because of this, I did not render $form['_csrf_token']->render() which should have been done. Due to which the login failed. Render the csrf_token field as well and you are good to go.

Rails query string with a period (or full stop).

I am currently trying to get a handle on RoR. I am passing in two strings into my controller. One is a random hex string and the other is an email. The project is for a simple email verification on a database. The problem I am having is when I enter something like below to test my page:
http://signup.testsite.local/confirm/da2fdbb49cf32c6848b0aba0f80fb78c/bob.villa#gmailcom
All I am getting in my params hash of :email is 'bob'. I left the . between gmail and com out because that would cause the match to not work at all.
My routing match is as follows:
match "confirm/:code/:email" => "confirm#index"
Which seems simple enough for what I need. I am having a hard time trying to figure out what the deal is and really how to even search for an answer. Any help or guidance would be greatly appreciated.
match "confirm/:code/:email" => "confirm#index", :email => /.*/
Also it would be better to set get method here, I think
get "confirm/:code/:email" => "confirm#index", :email => /.*/
Your problem is that Rails is trying to interpret .villa#gmailcom as a format specification (such as .html or .json). AFAIK, the standard work around (or at least the one I use) is to add this to your route:
:requirements => { :email => /.*/ }
This tricks Rails into not trying to be clever about what :email contains.
I'm not surprised that you couldn't find anything, googling for "#" or "." doesn't do anything useful.

Resources