Textbox validation for IP Address in WPF - c#

I'm making a WPF Application using C#. I want to put validations on integers (0123456789 and ".") only.. The textbox is supposed to contain an IP address... So need to ensure that user key in their correct "IP Address" before they click on the "Submit" button... How can I achieve it?
Thanks.

You can easily implement this using Wpf binding validation rules or by using a custom masked textbox
Check these links for exactly what you are looking for
http://geekswithblogs.net/QuandaryPhase/archive/2008/12/17/wpf-masked-textbox.aspx
http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-validation-rules
Hope it helps..

The following question link on StackOverflow contains a lot of pointers to MaskedTextBox implementation in WPF. You can use it to get IP Address input from user.
Where can I find a free masked TextBox in WPF?

Sounds like you're trying to implement a masked textbox, which is a textbox that auto-format data as the user types according to a specified pattern. Check this tutorial on how to implement this, since is not featured in WPF out-of-the-box: Masked TextBox in WPF

<TextBox IsReadOnly="False" Name="txtIpAddress">
<TextBox.Text>
<Binding Path="IpAddress" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True" >
<Binding.ValidationRules>
<Local:IPValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Public class IPValidationRule: ValidationRule
{
public override ValidationResult Validate(object value,System.Globalization.CultureInfo cultureInfo)
{
if(value == Rejex.Match(your condtion)
{
return new ValidationResult(true, null);
}
else
{
return new ValidationResult(false, "Invalid_Address");
}
}
}

Related

WPF validation without updating the data source

I have a TextBox displaying the time part of a DateTime:
<TextBox HorizontalAlignment="Left" Height="23" Margin="0,13,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Validation.Error="Validation_OnError">
<TextBox.Text>
<Binding Path="MyDate" StringFormat="HH:mm" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<c:TimeValidator></c:TimeValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Is it possible to do the validation on property change, and the conversion on lost focus?
I want to have the validation on property changed, but I want to have my data source updated on lost focus. Otherwise, the converter will kick in while the user is editing in the TextBox. This might be a problem if the values is 10:50 and the user deletes the last number, so that the value becomes 10:5. The converter will then convert this to 10:50. This is okay to do on lost focus, but not on property changed. But for the sake of the validator, i want to validate on property change so the user have the red border as long as the entered value is not valid.
Yes! I was just wrestling with this. AFAIK, there is no XAML combination for this--it must be done in the codebehind, and you need a direct reference to the element.
Element.GetBindingExpression(PropertyName).ValidateWithoutUpdate();
You'll probably want to check that GetBindingExpression doesn't return null; this will run any converters you have attached (presumably to supply the converted value to converters with ValidationStep set to ConvertedProposedValue), but will not update the source. And, of course, you'll have to call this in some event, perhaps TextChanged or somesuch. Here is the MSDN documentation for it: https://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpressionbase.validatewithoutupdate(v=vs.110).aspx
Use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
If you want to update it's source after check use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
if (expression!=null && !expression.HasError)
expression.UpdateSource();

How to check ValidationResults on button click

I have the a bunch of textboxes all with data validation as follows:
xaml
<TextBox>
<TextBox.Text>
<Binding Path="Name" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:Validation2/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
c#
public class Validation2 : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double result;
return double.TryParse(value.ToString(), out result) == true ? new ValidationResult(true, null) : new ValidationResult(false, "error");
}
}
This works nicely, whenever I put anything but a number in the textboxes an error pops up. Now I have a button to send the "form", I'd like the button to check if there were any validation errors before doing anything. How would I go about doing that.
Validation occurs before applying new value to source property. In your case - when you change property. In wpf there are also few more cases, but there is no OnFormClosing or similar. It's by design: control property may be bound to other control property (or several controls bound to same property), so validation occurs at latest when you change focus.
If you don't have cross-bindings, one property is bound to only one control, then you may utilize UpdateSourceTrigger.Explicit - call UpdateSource() for each binding when form is about to be closed.
Other solution would be to don't display errors as popups. Error status could be a red border or ! icon near.
I myself don't use validation mechanism at all. Instead, I have self-validating controls, to example, TextBox with property IsDouble to enable automatic validation for double values and property GetDouble, to parse value. I like more to validate everything at the end, while displaying actual status if validation will be ok or not to the user (red border, flashing caption, etc. per control).

TextBox UpdateSourceTrigger for PropertyChanged and LostFocus

Hello I have question about a wpf/xaml text box c# implementation.
I am trying to figure out how in my c# code to know what the UpdateSourceTrigger is being used.
I am a newbie, so I would very much appreciate if people are patient with me and helpful.
In my C# I need to know how the data in the Text box is trying to be accessed using UpdateSourceTrigger. I know the property changed when my OnPropertyChanged() is called. But I also need to know how if the user is trying to use LostFocus or PropertyChanged in the C# code. This is so I can do some special processing for either case.
xaml
<TextBox>
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}" Path="Name"
UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
c#
protected void OnPropertyChanged(string name)
{
// If UpdateSourceTrigger= PropetyChanged then process one way
// If UpdateSourceTrigger= LostFocus then process one way
}
Is there any other methods that get called when using LostFocus?
Thanks you
You will have to get a reference to your TextBlock and get the binding expression then you will have access to the Binding information
Example:(no error/null checking)
<TextBox x:Name="myTextblock">
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}" Path="Name"
UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
var textblock = this.FindName("myTextBlock") as TextBlock;
var trigger = textblock.GetBindingExpression(TextBlock.TextProperty).ParentBinding.UpdateSourceTrigger;
// returns "PropertyChanged"
another way of getting the binding object is:
Binding binding = BindingOperations.GetBinding(myTextBox, TextBox.TextProperty);
if (binding.UpdateSourceTrigger.ToString().Equals("LostFocus"))
{
}
else
{
}

Using WPF validation

I have a dialog in my project that the user enters some values in and when he hits OK I add an item to my database. I am using Entity Framework, so my adding to database code is something like this:
TransactionItem _item = new TransactionItem();
_item.DoctorID = (int)cmbDoctor.SelectedValue;
_item.TransactionCategoryID = (int)_dlg.cmbCat.SelectedValue;
_item.TransactionMethodID = (int)_dlg.cmbMethod.SelectedValue;
_item.Amount = int.Parse(_dlg.txtAmount.Text);
_item.DocumentID = _dlg.txtDocNum.Text;
_item.Info = _dlg.txtInfo.Text;
_item.Date = _dlg.dteDate.SelectedDate.ToString();
_db.TransactionItems.Add(_item);
_db.SaveChanges();
But the problem is there is nothing to bind and enable validating. I have tried making an empty object in my window and bind text box to it, but it had its own problems and didn't work as expected. I just want to when users enter values or when he hits OK, check if all of fields are valid (for example one of problems was if the user didn't enter any value, it is still valid even though the stringnotnull validator is enabled, but the most important problem was that it automatically set the textbox's text to null and mark it as a null value).
And I have made my own validator and here is a example of how I implemented them on one of my textboxes:
<TextBox Name="txtAmount" HorizontalAlignment="Left" Height="23" Margin="83,169,0,0" VerticalAlignment="Top" Width="224" Tag="T">
<TextBox.Text>
<Binding Path="myitem" ElementName="myWindow" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<Validators:StringNullValidationRule/>
<Validators:IsNumericValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Why don't you create a property in your viewmodel for each value the user needs to enter, and bind to it? Then you could use these properties when adding an item. For example:
ViewModel:
public int Amount { get; set; }
...
public void AddItem()
{
TransactionItem _item = new TransactionItem();
// ...
_item.Amount = Amount;
}
XAML:
<TextBox Name="txtAmount" HorizontalAlignment="Left" Height="23" Margin="83,169,0,0" VerticalAlignment="Top" Width="224" Tag="T">
<TextBox.Text>
<Binding Path="DataContext.Amount" ElementName="myWindow">
<Binding.ValidationRules>
<Validators:StringNullValidationRule/>
<Validators:IsNumericValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
I also recommend having a look at the INotifyDataErrorInfo interface (or the IDataErrorInfo interface if you're using .NET 4.0 or lower) to implement validations.
Use the IDataErrorInfo interface. You can implement it in your ViewModel or your Model class depending on your design. An example of how you can do it is in WPF: Validation made easy with IDataErrorInfo.
And I recommend you read this great Josh Smith article: WPF Apps With The Model-View-ViewModel Design Pattern. There you can see a good example of validation.

How to validate a UI in Silverlight?

My UI is simple. In a Silverlight 5.0 application, I'm using MVVM and I let the user adds many textboxes as he wants to add in a ObservableCollection<Model> and a Button.
Model just have one property and its datatype is an integer.
The data template for this model is just a simply textbox.
<TextBox Text="{Binding Number}" />
So the idea is, when all the textboxes does not have any error, the command is enabled, but if any model has an error, the command should be disabled.
How can I implement this validation?
Thanks in advance.
You can simply throw an exception in appropriate property`s setter:
public int Number
{
get {//...}
set {
if(value >= 10)
throw new Exception("Number should be less than 10");
_number = number;
}
}
And your binding should be:
<TextBox Text="{Binding Number, Mode="TwoWay" ValidateOnExceptions="True"}" />
FrameworkElement has BindingValidationErrorEvent, which can be used for implement enable/disable command logic. Remember to set NotifyOnValidationError to True for your binding.
p.s.Also, i suggest you read about INotifyDataErrorInfo

Categories

Resources