Disable mvc3 client-side validations under certain conditions - c#

I am building a search form which needs multiple fields. A radio button indicates which fields are required for input like so :
[ ] Field 1
[.] Field 2
Field 3
[ ] Field 4
In the above case, Field 2 and Field 3 are now required since the associated radio button is checked. To accomplish this, I have implemented the RequiredIf validation attribute, and it works properly.
My problem are the other validations. In this case, Field 1 also has a minimum length validation. If Field 1 has any value that does not respect the minimum length validation, the form is now invalid and cannot be submitted.
I need a way to disable validation on the fields that are not required. (And also be able to set them back as another radio button is checked).
The fields cannot be set to "disabled=disabled" which solves the issue because of client requirements.
I have tried removing the data-val attributes or setting them to false on the said fields, then parsing my form again, failing miserably.
Edit: Just making sure. The problem is client-side validations.

Remember that there are 2 validations happening: client and server side. Hence, removing the data-val attribute will not help.
Now, in your models I reckon you are using [attributes] to add these validation rules. I don't think this method will not let you do conditional validations.
In this case FluentValidation can help you. http://fluentvalidation.codeplex.com/
It is quite simple to do, and you should be able to do something like:
RuleFor(model => model.Field).NotEmpty().When(model => model.FieldEnabled);

Setting the fields as "disabled" works as intended. The client has changed his mind about this requirement. Sometimes it is the best solution.
This is still open for better solutions.
Edit :
I had not thought about searching for doc on the validation plugin. There seems to be some pretty interesting methods available to use like rules ( "remove", rules ).

Related

Validation of two sets of controls

ASP.NET WebForms 4.51
Having read things like How to validate two groups of controls with 1 button and a validation group?
I have a form with the following logical inputs:
Name (TextBox)
Last Name (TextBox)
Profession (Drop Down List)
Profession has the following items:
Bus Driver
Taxi Driver
Not Applicable
Now based on the profession I display a number of other text fields. I have required field validators on all the fields 1..3 as well as the fields for the profession (4..8).
I have a single submit button which triggers the validation. So my question is what is the easiest way to validate controls: 1..3 should the selection be Not Applicable for profession and 1..8 for the other professions from a single button.
I can think of a couple of ways but they are all "messy" and I was looking for a better approach:
1) Have two required field validators per field - one when validating for Not Applicable and one for when a profession is selected. Toggle the validation group when the profession is selected for the button.
I tried this but it does not seem to work as I still get both validators firing per field.
2) Write custom client side validators that take into account what is selected in the drop down for profession.
A maintenance nightmare. I would prefer to use any built in functionality MS provides.
So has anyone got any suggestions on how to validate the same sets of controls differently based on what has been selected in another control?
You could write a simple javascript validation script. You can not validate the javascript on serverside using "page.Isvalid".
Your only option is to write a custom validator. I just don't know why that should be a maintenance nightmare. If you're using the javascript validation you should validate the values in the code behind anyway. Otherwise the user could just disable javascript and enter anything he wants.
Hope it helps...

MVC 3 unobtrusive javascript validation when textbox has a default value

So I have a form working quite well with MVC 3, DataAnnotations and Unobtrusive javascript. However, I want to put a "watermark" on my input fields so that for example, the First Name textbox is populated with a value of "First Name" by default. When the user clicks on it, the value disappears and if they move off the field without entering anything, "First Name" appears again. Also, I have this implemented and working well.
My question has to do with the [Required] attribute on the FirstName property of my view model. If the user submits the form, by default that field has "First Name" in it so it passes the "Required" validation.
What's the best way to deal with this...I'm thinking of a few options:
1) Inject some jQuery to fire before the unobtrusive JS validation that clears the watermarks so that when the validation fires, those fields that have default values in them are blank. I'm not sure this is possible. Can you somehow inject a function before unobtrusive JS runs its validation?
2) Modify the [Required] attribute or create a new one to accept a default value and then compare it to see if they match. This raises a few issues in that I now have my default value specified in multiple places, one in the UI and one in code and that feels wrong.
3) Create a new "Watermark" attribute that I decorate a property with that specifies the default value for that field. Create a new HTML helper (instead of TextBoxFor) that looks for this attribute and emits the appropriate attributes to the tag. Modify or create a new [Required] attribute that looks for the existence of [Watermark] on the same field. This keeps the "Default value" in one place and keeps with DRY principles, but it feels like I'm putting UI elements into code (watermarks are purely visual) and it also feels like an overly complex solution for what should be a simple issue.
Any thoughts?
Each has it's pros/cons. I like to keep this client side and have used the following.
Use the HTML5 placeholder attribute and for browsers that support it you don't have to do anymore.
<input type="text" placeholder="First name" />
For browsers that don't...
On every page we have some compatability script for browsers that don't support certain features. In this case it's a little bit of JavaScript and jQuery that detects if the browser supports the placeholder attribute. If it doesn't it sets the field value to the placeholder value, sets the styling and adds the appropriate focus/blur event handlers. The focus/blur event handlers set the field value appropriately.
Then on your client validation script check that field value doesn't equal the placeholder value.
In your case this would mean modifying your unobtrusive JS validation to check the field value doesn't equal the placeholder value
I would probably go with #2, I think you could go about doing this in such a way that you do not need to specify the default value more than once. Also, if you wanted to validate that a user name was not taken you could use remote validation and then just check if the name was already taken or was the default name so you could get the behavior you wanted for free.

Field validators in asp.net

Is it possible to have "Required Field Validator" controls to validate more than one field (example I have 12 textboxes that are required. I want to try an avoid having 12 RFV controls. If a validation does get triggered, is there a way to display a customized message ("textA is empty" or "textB is empty") etc.?
You can create a custom validator that goes through validates all the controls.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
The Required Field Validator can only validate one control at a time.
You cannot do that with a RequiredFieldValidator; you could write your own CustomValidator to do that, but the validation would be on the server side rather than on the client side.
Multiple Fields Validator - An ASP.NET Validation Control is what you need.
As mentioned by everyone else you can create your CustomValidator that can validate on the client side and on the server side. There are couple of things that you must keep in mind.
1) Make sure to expose your client script as a Web Resource. This will enable the script to be cached by the browser.
2) Use a certain attribute to target certain TextBoxes. This can be performed by giving them a certain class which will be validated in your Custom Validator control.
Hope it helps!

Custom validatior in ASP.net

I'm working on an ASP.NET/C# app.
I have 2 text boxes and I need to validate if the input text for both of them are not both null
ex:
if(string.IsNullOrEmpty(TextBox1.Text) && string.IsNullOrEmpty(TextBox2.Text) )
//FAIL!!!
else
// OK!
that is, at least one txtBox has values
I was planning on using a custom validator but it seems that the validation function only gets called when something is written on the textBox i'm using has the 'control to validate'. Now, that doesn't work for me since I want to show an error message when both text boxes are empty. Is there a way to make the validation function to be called with, for example a postback? Or is there any other better approach to this case than the custom validator?
tks
If you set the 'ControlToValidate', then the validator will not fire if that control is empty. However, for a CustomValidator you can leave that empty so it will always fire.
Because the built-in validators only analyze the state of their own controls, you are forced to go with a CustomValidator for this functionality. I don't know of any better approach that still uses ASP.NET server-side validators. As Hans said, be sure to leave ControlToValidate empty, and then do the validation as in your code sample.

ASP.NET Multiple Field Validation

In ASP.NET 2, I've used Field Validators, and RequiredField validators, but I'm unsure of how to handle a case like this.
I have two check boxes on a page, and I need to be sure that at least one of them is set. So, if you look at in binary, it can be 01, 10 or 11, but it can not be 00. My question is, what the best way to do this with checkboxes?
Can the normal ASP Validators handle this, or would I need to create an integer value like mentioned above, hidden somewhere and use a RangeValidator do a test to make sure THAT value is never zero?
Worst case you can write a CustomValidator the can do whatever you like. Sounds like what you need is along the lines of:
isValid = Check1.Checked | Check2.Checked
Use CustomValidator
This control (written by me) supports CheckBox and CheckBoxList:
http://www.codeproject.com/KB/validation/AtLeastOneOfValidator.aspx
Just add it to visual studio, drop it on your page, and add your checkboxes to it's Controls list. It will work like any other validator control.
Custom validator is the obvious solution. Also, when using a custom validator you should also check for validity on the server side just in case the javascript fails due to some reason.
P.S.: Don't always trust what the client(browser) sends you.
Here is an article I wrote regarding this exact issue. I also wanted to validate multiple controls which was easy using the CustomValidator but one of the issues I was not happy about is that if you corrected the validation issue the error did not go away until you posted back.
I figured out a way to hide the error message and revalidate and wrote a small blog entry about it. Check it out and see what you think.
http://coding.infoconex.com/post/ASPNET-CustomValidator-that-validates-multiple-controls-using-both-Server-Side-and-Client-Side-scripting.aspx

Categories

Resources