Additional validation in ASP.NET

I have a page with three radio buttons, depending on the selected button. I need to validate some controls (using required fields). Other than using custom validators, is there a way to do this?

thanks

0


a source to share


4 answers


ASP.NET validators offer a client-side API that allows you to:

  • check client side
  • Connect the client validator system.
  • Enable or disable client-side validators.


Function syntax ValidatorEnable

:

 ValidatorEnable(rfvMyValidator, boolState);

      

+2


a source


Add OnSelectedIndexChanged to RadioButtonList (or CheckedChanged if they are separate radio button controls)



In the code behind, .Enable

and .Disable

special required fields for validation.

+1


a source


I tried this with a small example and it worked for me:

I have

-2textboxes: TextBox1 and TextBox2

-RequiredFieldValidator: RequiredFieldValidator1 with ControlToValidate = "TextBox1"

-RadioButton: RequiredFieldValidator1

This code is generated by RequiredFiledValidator:

<script type="text/javascript">
//<![CDATA[
var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");
RequiredFieldValidator1.controltovalidate = "TextBox1";
RequiredFieldValidator1.errormessage = "RequiredFieldValidator";
RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
RequiredFieldValidator1.initialvalue = "";
//]]>
</script>

      

I want the user to click on RadioButton1 to switch validation to TextBox2.

This is how I did it:

 protected void Page_Load(object sender, EventArgs e)
        {
            RadioButton1.Attributes.Add("onclick", "RequiredFieldValidator1.controltovalidate=\"TextBox2\"");
        }

      

+1


a source


Waleed, you are not specifying whether you are using ASP.Net or ASP.Net MVC forms.

If you are using ASP.Net MVC the answer is pretty simple ...

First, you must create a ModelView class that must include boolean attributes appropriate for your radio traffic.

Just use the Foolproof authentication library that is available on Codeplex and should work due to the downside of your problem: https://foolproof.codeplex.com/

It supports, among others, the following "requiredif" attributes / decorations:

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

      

It's easy to start:

  • Download the package from the provided link
  • Add link to .dll file.
  • Import the included javascript files
  • Make sure your views reference the included javascript files from your HTML for unobtrusive javascript and jquery validation.

All you have to do is decorate your fields, which should be conditionally validated with an attribute [RequiredIfTrue]

that should point to the corresponding radioblock value in your ViewModel.

0


a source







All Articles