ragunathjawahar / android-saripaar Goto Github PK
View Code? Open in Web Editor NEWUI form validation library for Android
License: Apache License 2.0
UI form validation library for Android
License: Apache License 2.0
This feature is not implemented yet.
I get the following error:
No rules found. You must have at least one rule to validate. If you are using custom annotations, make sure that you have registered them using the 'Validator.register()' method.
This is my code:
@NotEmpty
@Email
@InjectView(R.id.email)
TextView email;
@NotEmpty
@InjectView(R.id.password)
TextView password;
@InjectView(R.id.button)
FButton button;
And then onCreateView
:
validator = new Validator(this);
validator.validate();
I'm using 2.0 snapshot
compile 'com.mobsandgeeks:android-saripaar:2.0-SNAPSHOT'
Any thoughts?
Please could you tell me how could i use this library with native fragments
not fragments from support library (not support.v4)
Thanks in advance
Ability to inject error message by specifying string value from string resource from strings.xml
like @required(order = 1, message = R.string.my_message)
Adding the lib to maven central, would be great!
How to change the validator background?
I want use my image to replace the default background, how can i do this?
It would be FANTASTIC too see this somehow, the 'AndroidFloatLabel' pattern edittexts return an instance of viewgroup, and as such cannot have a saripaar annotation. in code the edittext for the float label group is accessed via
label.getEditText().xyz
Perhaps being able to add validation rules via code would suffice?
.setValidationRule(required) or similar
Hi,
There is a simple issue that when I enter white spaces in a field that has the annotation @notempty, validation rule just passes normally and no error is displayed, while the rule should fire validation error saying "This field is required".
Please advise.
I defined a new rule (Spinner Choice Required), which was super easy. Now, I would like to be able to use it through an annotation. Right now I'm adding it programmatically, which I don't like.
Looking at the code, the builtin annotations seems to be hard coded. Am I missing something here?
I am not sure if "string format" is the right name for it. Basically what I need is an ability to do this.
in the rule:
@TextRule(order = 1, minLength = 5, messageResId = R.string.min_characters)
EditText username;
in the strings.xml
:
<string name="min_characters">%d characters minimum</string>
What I expect is validation error message should gives me message 5 characters minimum
but the actual result is %d characters minimum
(the %d is not parsed).
Is there any way to achieve this? Hopefully this feature will be added in the future (if has not already)
Thanks
note: this proposed feature should also supports another validation annotations
Hi Ragunath,
Thanks for this great library.
Let me try to tell the situation with an example.
We have a form and we have two buttons: Calculate and Save. Both must check for validation before doing any operation but they will act differently when the validation succeeds. "Calculate" makes a calculation and prints the result to a Textview while "Save" creates an object from form data and saves it to somewhere.
It would be great if we can differentiate the validation sources in success callback(maybe in other callbacks, too).
Like this:
validator.validate(int which);
void onSuccess(int which) {
if(which == CALCULATION) {
calculateAndPrint();
} else if(which == SAVE) {
createObjectAndSave();
}
}
Thanks.
Cannot find v2 in maven
Your library is great and I am just playing around with V2.
Can I somehow stop the validation process for a view with multiple rules after the first error has occured?
I have a use case with two rules for one edit text field. The first rule checks if the user name is at least 5 characters long. The second then calls a backend service to check if this user name is still avaliable. So I only want the second rule to be fired if the first one is okay.
Sorry if I missed something but based on the code in the Validator I have not seen such an option.
Hi,
How can I unhide the Validation failure pop ups shown during failure after validation succeeds ?
@Override
public void onValidationSucceeded() {
Toast.makeText(MatchBotApplication.getAppContext(), "Yay! we got it right!", Toast.LENGTH_SHORT).show();
// Some code to unhide all the popups shown in the failure callback
}
@Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
((EditText) failedView).setError(message);
} else {
Toast.makeText(MatchBotApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
}
Hello,
I wonder if there's possibility to validate only one of the annonated Views at a time (ideally on focus lost)?
More precisely: I have 3 EditText views (lets say: etA, etB, etC) in my form. What I want to achieve is when the User fills field etA and then switches focus to etB, the validator only validates etA and then, after user fills etB and switches focus to etC it validates etB.
I don't want to use callback ValidationListener.
I've faced with problem using an android-saripaar.
After validate()
called, my fields are not resolved (i checked it by viewing contents of Validator
object).
I think its happening because i'm using AndroidAnnotation framework, that makes my Activity class base class of actual Activity used.
For example:
package com.some.example;
@EActivity(R.layout.main)
public class MyActivity extends Activity {
@Required(order = 0)
@TextRule(order = 1, minLength = 3, messageResId = R.string.error_min_length)
@ViewById(R.id.name)
EditText name;
private Validator validator;
public void onCreate() {
super.onCreate()
validator = new Validator(this);
validator.setValidationListener(new SomeInputValidator())
}
// some code here ...
void itsTimeToValidate() {
validator.validate();
}
}
AndroidAnnotations creates some derived class called MyActivity_
, that is used in execution. I think problem hides near getSaripaarAnnotatedFields
method.
I'm trying to get the error message for setError Edittext method.
PD: Sorry my english is bad
First of all, this is a great library!
But I have a problem validating email with +
sign. I see, that a fix is already in repo, but not in the latest release.
Do you plan any minor release to maven?
When used with Kotlin, the library doesn't seem to pick up annotations. Investigate and add support.
I have a form where User Either has to enter username or mobile number in edit text. Is there any current feature that can help me ?
hey,
what I am proposing is , is there any way to call a local method from annotation. like
@MinLength(value = 3, myMethodFailed(),myMethodPassed());
private EditText mEditName;
I am saying this because in my app I am not showing inbuilt error message. and also on error, I turn the field red and on passed, I turn field back to normal. So I am asking if there is any way to implement any custom feature, please help me. Provide me some help with gist or something as I am noob to annotations
thankyou
Hi,
I recently came across a small issue while using this helpful framework.
The NumberRule raises a NumberFormatException when used with the 'gt' attribute for Integer validation.
Consider the following example:
@NumberRule(order = 1, type=INTEGER,gt=0)
EditText etOrderQuantity
This raises an java.lang.NumberFormatException: For input string: "0.0"
I think this is because 'gt' attribute is of type double and is parsed to an int value in AnnotationToRuleConverter.java line 177
String gtNumber = String.valueOf(numberRule.gt());
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.gt(null, Integer.parseInt(gtNumber))); break;
Also, I think this exception will be raised using attributes 'lt' and 'eq' too.
First of all, nice library! Quite powerful as it is. The main drawback that I'm experiencing is that I need to validate all fields on 1 go, rather than stopping at an error. As a result, I'd love to have onValidationFailed() pass a List<Rule<?>> failedRules
.
Thanks, again!
Hi i have problem with my release version where I use proguard. In debug everything works fine.
When I try to Call:
validator.validate();
they throw:
java.lang.NoSuchFieldError
at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:688)
at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:663)
at libcore.reflect.AnnotationAccess.annotationSetToAnnotations(AnnotationAccess.java:633)
at libcore.reflect.AnnotationAccess.getDeclaredAnnotations(AnnotationAccess.java:161)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:234)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:104)
at com.mobsandgeeks.saripaar.Validator.getViewFieldsWithAnnotations(SourceFile:478)
at com.mobsandgeeks.saripaar.Validator.getSaripaarAnnotatedFields(SourceFile:453)
at com.mobsandgeeks.saripaar.Validator.validateAllRules(SourceFile:346)
at com.mobsandgeeks.saripaar.Validator.validate(SourceFile:156)
at pl.someclass.fragment.RegistrationFragment$1.onClick(SourceFile:92)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchFieldException: LONG
at java.lang.Class.getDeclaredField(Class.java:886)
at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:685)
... 20 more
java.lang.NoSuchFieldException: LONG
at java.lang.Class.getDeclaredField(Class.java:886)
at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:685)
at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:663)
at libcore.reflect.AnnotationAccess.annotationSetToAnnotations(AnnotationAccess.java:633)
at libcore.reflect.AnnotationAccess.getDeclaredAnnotations(AnnotationAccess.java:161)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:234)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:104)
at com.mobsandgeeks.saripaar.Validator.getViewFieldsWithAnnotations(SourceFile:478)
at com.mobsandgeeks.saripaar.Validator.getSaripaarAnnotatedFields(SourceFile:453)
at com.mobsandgeeks.saripaar.Validator.validateAllRules(SourceFile:346)
at com.mobsandgeeks.saripaar.Validator.validate(SourceFile:156)
at pl.someclass.fragment.RegistrationFragment$1.onClick(SourceFile:92)
Has anyone else had a similar problem?
Hi Sir,
I came across with your library and I want to try it out. In your instruction Quick Start-step 1, there is an annotation, @notempty , and when I open the link of your annotations, I can see several classes.
I tried above instruction but I can't find the class @notempty, so I tried copying the code in your NotEmpty.class and create a copy in my project, but @ValidateUsing(NotEmptyRule.class) could not be found either.
So, I downloaded your main project and I found all those files.
My question is, why I could not find those files in your jar? do I need to include the source as dependency in my project?
Thank you so much.
Currently I have add the following to my activity class to make a regex validation optional:
private static String getText(final TextView textView, final boolean trim) {
CharSequence text = null;
if (textView != null) {
text = textView.getText();
text = trim ? text.toString().trim() : text;
}
return text != null ? text.toString() : null;
}
public static Rule<TextView> optionalRegex(final String failureMessage, final String regex,
final boolean trimInput) {
if (regex == null) {
throw new IllegalArgumentException("\'regex\' cannot be null");
}
return new Rule<TextView>(failureMessage) {
@Override
public boolean isValid(TextView textView) {
String text = getText(textView, trimInput);
if (text == null || text.isEmpty())
return true;
else
return text.matches(regex);
}
};
}
and then add this before validator.validate()
call:
validator.put(referralMobile, optionalRegex("Please enter the mobile number again", "[0-9]{8}", true));
validator.validate();
Is there a simpler way? If not, can you consider adding an optional
argument to the existing annotations? Alternatively, I understand @Email
and @IpAddress
is already optional, i.e. they ignore empty EditText
widgets by default and need the @Required
annotation to make inputs required. So to be consistent, make all the other annotations optional by default?
hi
Is there any chance that i can validate my apps preferences fields using saripaar? For example i need to not allow the user to enter no less than 100 on a EditTextPreference number field.
Any suggestions are welcome
Things like email regex can be hard to get 100% for certain edge cases and something like Apache Commons Validator[1] provides the core validation that you could wrap and extend for Android. Just a suggestion for future versions. I like your ideas so far though. I think it's also possible you could mod the Android XML and add a validation field directly as an alternative to users doing it all programmatically, but would have to use some custom views extending the base ones[2]
[2] http://developer.android.com/training/custom-views/create-view.html
Rules ordering is done on validation and custom rules adding occurs before. If so, custom rules always have more priority and that's not true.
Maybe, it's better to store order
inside the Rule
? So developer could add custom rules at runtime with proper priority.
Could you add the ability to use resources in text annotations?
Hi,
The NumberRule with gt attribute for Double type performs comparision via the gt(..) function at line 434 in Rules.java. The code presently checks expected > actual
if (actualDouble != null) {
valid = actualDouble.matches(REGEX_DECIMAL) ?
expectedDouble > Double.parseDouble(actualDouble) : false;
}
If I want a view to contain a double value greater than 0 and the user enters say 34. Then this function will return false and the validation will fail. I think it should be
Double.parseDouble(actualDouble) > expectedDouble : false;
Hi:
how to validate tel no
Hi,
android-saripaar is great, already implemented in one of my projects and now in another.
this project is a one screen app with two panels - one for login and one for registration. there are two layouts - one containing the login fields (email, password) and the other one containing the registration fields) . only one layout is visible at a time and the user clicks a button to switch between them according to his needs.
I need the validation to work only on the currently visible layout. I couldn't find a way to group validations so i'm looking into alternatives. would setting the visibility of a the fields to false in the hidden layout be enough in order not to not trigger the validation for them (having only the visible fields validated)?
Thanks,
Dan
REGEX_EMAIL in the rules class needs to allow hyphens in the domain name part. [email protected] is a valid email address.
I think it would be better if validate
will return boolean value. true
means that validation have been succeeded and false
means that validation have failed.
Also, it will be nice if default implementation of ValidationListener
will be provided, some like this:
public class DefaultValidationListener implements ValidationListener {
public void onSuccess() {
}
public void onFailure(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
failedView.setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
public void preValidation() {
}
public void onValidationCancelled() {
}
}
Currently the Validator.validate()
method will stop validating when it finds the first field that failed validation.
However, I would like to get back a list of all fields that failed validation and then perform setError on all of them. Is there a way to do this with saripaar?
if we one edittext validations are satisfied than skip other editexts validations,is it possible?
@required(order = 1, message = "Please enter name")
private EditText et_name;
@required(order = 1, message = "Please enter sirname")
private EditText et_sirname;
for example i need validation that either one of them feilds sholuld be validate
after that skip other feild for validations
Say you have five EditText fields, all set as required. Then, on the first attempt to submit, none of them validates. The user fix the first field then focus on the next one.
You can still see the error icon applied to the (now) valid one.
If there is a View
that is not annotated with one of the Saripaar / custom annotations, the QuickRule
for that view does not get picked up.
In annotation:
Required (Order = 1)
email (Order = 2)
private EditText emailEditText;
order is defined
if I have:
validator.put (EditText, Rules.required ("message", true));
no defined order
How to define order from code?
Thanks for a great library.
Can the pop-tip presented at validation be styled?
Hi,
I think it would be great if it was possible to add string resource id's as messages in the annotations. Currently it is possible if you pass the ID as a string and then concat it back to an INT when you want to get the message, but it might be nice if you could just do something like:
@Email(order = 3, messageId = R.string.email_error)
t would be nice if you provide some sample examples or activity. I found it difficult to implement. thanks
First i want to thank you for your huge effort on making form validation possible and easy to go.
Is there any plans on enabling localization support in android-saripaar so validation messages could be displayed in desired language(s)?
the following code wont work:
@Email(order = 3, message =getString( R.string.invalid_email_address));
Can I help by writing some code?If yes,how?
Hi Raghu,
I have a requirement where i hide few fields based on some criteria &
I don't want validation to happen on those EditTextViews where it's visibility is hidden through setVisibility(View.GONE);
is it possible through android-saripaar.
Mikka Nandri.
If I validate emails like: [email protected] error message apper. But the domains with "-" is ok.
Can you change reg expression like this:
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/
If validation is complete and onValidationFailed function is executed:
((EditText) failedView).setError(message); -EditText field is in red Error.
Next user change this field and click on Submit button. Field map is re-validated and value of this field is valid (error appear on next field) but the old error in EditText exist too.
2 error fields is in red (first is valid but the error is not removed)
Can you add public method to get private Map<String, Object> mProperties;
and I can in mProperties loop to set on all field for validation:
textView.setError(null);
While it actually is.
Encountered when using it for the official Wikipedia app. Downstream bug at https://bugzilla.wikimedia.org/show_bug.cgi?id=64615
Thanks for the cool library!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.