how to accept email or phone number in the single edit text - android-edittext

I have only one edit text field to accept email or phone number. how to change the input type based on the 1st character ? based on user input i need to perform different operations.. The main thing is i should identify whether that is email or phone number. how to do this?

In your, EditText set a TextWatcher which calls a function to check if the text is email or is a phone number.
Get the text from your TextView like :
String text = textView.getText().toString();
Adding the listener to your TextView :
textView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(....){}
#Override
public void beforeTextChanged(...){}
#Override
public void afterTextChanged(Editable s) {
if(isEmail(text)){//do your stuff}
if(isPhone(text)){//do your stuff}
}
}
Your methods would look something like this:
public static boolean isEmail(String text) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern p = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
return m.matches();
}
public static boolean isPhone(String text) {
if(!TextUtils.isEmpty(text)){
return TextUtils.isDigitsOnly(text);
} else{
return false;
}
}
This might not be possible with just checking the first digit. Though you can put validations inside onTextChanged method.

Novo Lucas's answer is correct.
My Views :
First thing is that you can't know input type using the first letter cause some email addresses begin with numbers.
On button click you can identify type by knowing if the text contains only numbers or alphanumeric characters. For more info about code you can search it on Google. I will try to add code after some time. Good Luck

Related

Unable to get a mapping value

I'm trying to implement a small contract to upload file hashes on the blockchain along with the file description and the sender address. I've programmed this small contract :
pragma solidity^0.4.17;
contract hashes {
mapping(uint => string) descriptions;
mapping(uint => address) senderAddresses;
function uploadHash(uint _hash, string _description) public {
require(bytes(descriptions[_hash]).length == 0);
descriptions[_hash] = _description;
senderAddresses[_hash] = msg.sender;
}
function getHash(uint _hash) public returns (address, string){
return (senderAddresses[_hash], descriptions[_hash]);
}
}
I think uploadHash works as expected since when I'm uploading the same hash twice I get a revert. However when I'm trying to use getHash, I don't get any return value. The results are the same when I'm calling from remix or directly from web3.
Thanks in advance !
I believe you're missing the view modifier
function getHash(uint _hash) public view returns (address, string)
Remix will not show the res next to the input boxes unless you use the view modifier.

unable to Validate Custom components in SmartGWT

I am unable to get my custom compoenent to be validated in the dynamic form. I tried many versions but it is not working as expected. For e.g. either the label is not showing in BOLD to indicate the field is mandatory and it aloows to save the form without entering anything in the field. Only when the user enters something in the field and deletes it, then the red icon is displayed to the user that the field is mandatory.I dont know what i am missing. please help. code is below
telnumber = new CustomTelephoneTextItem();
telnumber.setName("tel");
telnumber.setTitle("Tel");
telnumber.setTitle(nerpweb.clientFactory.getMessages().tel());
Below is my Custom TextItem which i am using in the above class
public class CustomTelephoneTextItem extends CanvasItem
{
textField_value = new CustomIntegerItem();
textField_value.setShowTitle(false);
textField_value.setWidth(100);
textField_value.setRequired(true);
form.setItems(textField_value, textField_code);
form.validate();
setWrapTitle(false);
this.setCanvas(form);
First, if you want to item title showin bold, you must call item's setRequired(true).
in your code is telnumber.setRequired(true);
Second, if you want to validate item on form.validate(), you must override validate() function in your item and write validation code in this function.
in your code is call form.validate() in CustomTelephoneTextItem validate() function
Here is the code to be implemented to validate custom component
This code will go in your Custom component which you will implement
#Override
public Object getValue()
{
if (validate() && textField_value.getValue() != null)
return textField_value.getValue();
return null;
}
#Override
public void setRequired(Boolean required) {
super.setRequired(true);
}
#Override
public Boolean validate() {
return super.validate();
}
#Override
public void setValidators(Validator... validators) {
textField_value.setValidators(validators);
}
Then in the class where you will create the custom component you will call the setRequired() method,like so
telnumber.setRequired(true);

Validation icon not shown in Table fields

When I enter edit mode of my Table, I want the data validation exclamation mark icon (!) to be shown as soon as the user goes out of bounds of any of the validation constraints.
First, a couple of notes:
I'm using Vaadin 7, so the Bean Validation addon sadly won't work.
The data validation works as intended.
Now, I have a perfectly working table for which I am using a BeanItemContainer to keep my Person beans inside.
The code for the table and the TableFieldFactory looks something like this:
table.setContainerDataSource(buildContainer());
table.setTableFieldFactory(new TableFieldFactory() {
#Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
TextField field = (TextField) DefaultFieldFactory.get().createField(container, itemId, propertyId,
uiContext);
field.setImmediate(true);
if (propertyId.equals("firstName")) {
field.addValidator(new BeanValidator(Person.class, "firstName"));
}
return field;
}
});
The Person bean looks as follows:
public class Person {
#Size(min = 5, max = 50)
private String firstName;
... setters + getters...
}
The problem is that when I type something in the firstName field and then press enter or blur/unfocus that field, no indication whatsoever of error is shown. I have to mouseover the field to see that something is wrong.
My question is two folded...
How do I get the exclamation mark icon to appear when the field is
invalid? (This works for a normal TextField that is not in a Table)
Is there a way to get an immediate response from the invalid field
(show the icon) (i.e. immediately after you type under 5 chars,
without having to press enter or blur/unfocus the field in
question).
Would be great if I could have both questions answered! =)
Thanks in advance!
The Caption, Required Indicator (the red asterisk) and - most importantly here - Error Indicator (exclamation mark) are actually provided by the layouts containing the component, not the component themselves. When editable components are displayed in a table, they are displayed without a layout - that's why no error indicator is displayed.
If I were trying to square this circle, I would look at creating a CustomField as a wrapper for the editable field - and within that CustomField display an error indicator when the wrapped/delegate field becomes invalid. I've not tried this - I've not used editable fields in a table at all - but should be fairly easy to do.
Add a TextChangeListener to the field in FieldFactory, and call field.validate() in the listener. Note, though, that field.getValue() value is not normally changed until blur/unfocus, ergo the validator will be validating the old value - unless you do field.setValue(event.getText()) in the listener. See this post on the Vaadin forum for more details.
This is the sort of thing I meant for a validating wrapper - not tried using it. You'll see initComponent simply returns the field inside a FormLayout, which should give you the icon(s) you're seeking. (You may need to delegate more methods from ValidatingWrapper to delegate than I have- but quick look suggests this may be enough.)
You'd then wrap the field in your tableFieldFactory (second code block)
public class ValidatingWrapper<T> extends CustomField<T> {
private static final long serialVersionUID = 9208404294767862319L;
protected Field<T> delegate;
public ValidatingWrapper(final Field<T> delegate) {
this.delegate = delegate;
if (delegate instanceof TextField) {
final TextField textField = (TextField) delegate;
textField.setTextChangeEventMode(AbstractTextField.TextChangeEventMode.TIMEOUT);
textField.setTextChangeTimeout(200);
textField.addTextChangeListener(new FieldEvents.TextChangeListener() {
#Override
public void textChange(FieldEvents.TextChangeEvent event) {
textField.setValue(event.getText());
textField.validate();
}
});
}
}
#Override
public Class<? extends T> getType() {
return delegate.getType();
}
#Override
protected Component initContent() {
return new FormLayout(delegate);
}
#Override
public Property getPropertyDataSource() {
return delegate.getPropertyDataSource();
}
#Override
public void setPropertyDataSource(Property newDataSource) {
delegate.setPropertyDataSource(newDataSource);
}
}
table.setContainerDataSource(buildContainer());
table.setTableFieldFactory(new TableFieldFactory() {
#Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
TextField field = (TextField) DefaultFieldFactory.get().createField(container, itemId, propertyId,
uiContext);
field.setImmediate(true);
if (propertyId.equals("firstName")) {
field.addValidator(new BeanValidator(Person.class, "firstName"));
}
return ValidatingWrapper(field);
}
});

How to get input text into the listfield of autocompletefield in blackberry?

I want to make something like the contact selection in OS 5.0 while composing message
For that I have made an autocompletefield with contacts as datasource. Now I want to add the user input, that is what he types into the drop down list which appears in autocompletefield so that if the contact is not available in the phonebook he can use the number.
Check this link: How to get the selected item as String in a Blackberry AutoCompleteField?
public void onSelect(Object selection, int type) {
super.onSelect(selection, type);
if(selection != null) {
String selectionAsString = getEditField().getText();
// Do whatever else you need to do with the String.
}
}

Text on TextBox with UpdateSourceTrigger=PropertyChanged is not updated when coercion of text input results in unchanged source value

I have a text box whose Text property has a TwoWay MultiBinding with UpdateSourceTrigger set to PropertyChanged. The first Binding is to a dependency property (Value) which has a PropertyChangedCallBack function that rounds the value to one decimal place.
The purpose of the text box is to perform the rounding as the user types rather than when the text box loses focus, hence why UpdateSourceTrigger is set to PropertyChanged.
The problem I am having is that if text is entered that does NOT result in Value changing, the Text property and Value become out of sync. Only if the rounding operation causes Value to change does Text get updated on the fly. E.g., if Text and Value are both 123.4 and the user types 1 after this, Value is rounded to the same value (123.4), but Text shows 123.41. However, if 9 is then typed after the 4, Value is rounded up to 123.5. And because of this actual change, Text is then updated to the same (123.5).
Is there any way of forcing a text box to update from its source even when the source hasn't changed since the last trigger? I have tried using BindingExpressionBase.UpdateTarget() but this only works when UpdateSourceTrigger is set to Explicit, which can't be used as Value no longer gets updated prior to a suitable time where UpdateTarget could be called (such as a TextInput handler). I have tried other methods such as explicitly updating the Text value from the bound Value, forcing an actual change to Value temporarily to invoke an update, but these "hacks" either don't work or cause other problems.
Any help would be greatly appreciated.
The code is below.
XAML snippet
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{local:NumberFormatConverter}"
UpdateSourceTrigger="Explicit"
Mode="TwoWay">
<Binding Path="Value"
RelativeSource="{RelativeSource AncestorType={x:Type Window}}"
Mode="TwoWay" />
</MultiBinding>
</TextBox.Text>
</TextBox>
C# snippet
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value", typeof(decimal), typeof(MainWindow),
new FrameworkPropertyMetadata(0m,
new PropertyChangedCallback(OnValueChanged)));
private static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
obj.SetValue(ValueProperty, Math.Round((decimal)args.NewValue, 1));
}
Converter class required
public class NumberFormatConverter : MarkupExtension, IMultiValueConverter
{
public static NumberFormatConverter Instance { private set; get; }
static NumberFormatConverter()
{
Instance = new NumberFormatConverter();
}
public override object ProvideValue(IServiceProvider serviceProvider_)
{
return Instance;
}
#region Implementation of IMultiValueConverter
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0].ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
var result = 0m;
if (value != null)
{
decimal.TryParse(value.ToString(), out result);
}
return new object[] { result };
}
#endregion
}
I did a little digging on the Internet, and it turns out this was broken in WPF 4. Someone with an almost-identical problem to me posted here:
http://www.go4answers.com/Example/textbox-shows-old-value-being-coerced-137799.aspx
'Answer 8' states this was broken in WPF 4 and suggests a solution, which is to actually use UpdateSourceTrigger="Explicit" but to handle the TextChanged event and call BindingExpression.UpdateSource() to force changes in the text box to be reflected in the underlying value as if UpdateSourceTrigger="PropertyChanged", as per this post:
Coerce a WPF TextBox not working anymore in .NET 4.0
I implemented this, but lo and behold there were further side effects, in particular that every keystroke caused the caret to jump to the start of the text box due to updating the source and raising a PropertyChanged event. And also, any leading or trailing zeros or decimal places entered with the intention of entering further digits would get wiped out immediately. So, a simple condition to check the parsed decimal value of the text box versus the underlying value resolved this.
The following event handler is all that was needed:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var tb = (TextBox)e.Source;
MultiBindingExpression binding = BindingOperations.GetMultiBindingExpression(tb, TextBox.TextProperty);
decimal result = 0m;
decimal.TryParse(tb.Text, out result);
if ((decimal)GetValue(ValueProperty) != result && binding != null)
{
int caretIndex = tb.CaretIndex;
binding.UpdateSource();
tb.CaretIndex = caretIndex;
}
}

Resources