Cannot validate textfield using codeigniter validation using callback - codeigniter

I want to validate from and to text fields using codeigniter validation. I have created
validateSchedule function that will validate on callback but here validation is not
working it is working only for required condition.
public function validateSchedule()
{
$fromDate=$_POST['from_date'];
$toDate=$_POST['toDate'];
if(empty($toDate) || empty($fromDate))
{
return TRUE;
}
else
{
$diffNoof_days = 10;
if(strtotime($fromDate) > strtotime($toDate)){
$this->form_validation->set_message('validateSchedule','from_date_must_be_smaller_than_to_date');
return FALSE;
}else if(strtotime($fromDate) == strtotime($toDate)){
$this->form_validation->set_message('validateSchedule','from_date_to_must_not_be_same');
return FALSE;
}else if($diffNoof_days>10)
{
$this->form_validation->set_message('validateSchedule','duration_should_not_exceed_10_days');
return FALSE;
}
}
}
$this->form_validation->set_rules('from_date','From Date','trim|required');
$this->form_validation->set_rules('to_date','To Date','trim|required|callback_validateSchedule');

You don't show the actual callback, so I'm speculating that you have named the method wrong by not removing the callback_ prefix. In other words, the definition
public callback_validateSchedule($str)
{
...
}
should be
public validateSchedule($str)
{
...
}
If I have guessed wrong please show the actual code for validateSchedule()

Related

Xamarin IOS InAppBiling plugin how to get receipt-data

I use Plugin.InAppBiling for In-App Purchase ios. I want to know Purchase receipt data.
here is my code.
private async Task<bool> MakePurchase(string productId)
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)
{
return false;
}
var verify = DependencyService.Get<IInAppBillingVerifyPurchase>();
var purchase = await CrossInAppBilling.Current.PurchaseAsync(productId, ItemType.InAppPurchase, verify);
if (purchase == null)
{
return false;
}
else if (purchase.State == PurchaseState.Purchased)
{
if (Device.RuntimePlatform == Device.iOS)
{
Console.WriteLine("CHECK");
if(verify == null)
{
Console.WriteLine("null");
}
else
{
Console.WriteLine($"{verify}");
}
}
return true;
}
return false;
}
finally
{
await billing.DisconnectAsync();
}
}
The payment process goes well. but verify is just return null.
I understood verify as receipt-data. It's right?
How do I get a base64 encoded string receipt-data?
The documentation you also link to clearly states that you need to implement IInAppBillingVerifyPurchase yourself. There is no implementation of this in the plugin.
So you need to create your own class and register it in the IoC container:
[assembly: Dependency(typeof(MyIAPVerification))]
public class MyIAPVerification : IInAppBillingVerifyPurchase
{
// implementation here
}
Only then will your verify instance not be null.

Laravel - SuperAdmin can't see other roles

I added this in my User model:
private $rank;
public function isSuperAdmin(): bool {
if ($this->rank >= 3) {
return true;
}
return false;
}
public function isAdmin(): bool
{
if ($this->rank == 2 || $this->isSuperAdmin()) {
return true;
}
return false;
}
public function isCustomer(): bool {
if ($this->rank == 1|| ($this->isSuperAdmin() || $this->isAdmin())) {
return true;
}
return false;
}
I have rank '3' which equals the isSuperAdmin() function. So when I do the following:
if (Auth::user()->isSuperAdmin())
This works as expected. However when I, as SuperAdmin, try to do the following:
if (Auth::user()->isAdmin())
It doesn't work at all, Laravel doesn't display whatever is between #if(Auth::user()->isAdmin()) in my views when I have the role SuperAdmin. This is the same for all the roles and I don't understand why.. what am I doing wrong?
Ps. I also tried the following in the isAdmin function, which also doesn't work:
if ($this->rank >= 2 || $this->isSuperAdmin()) {
After I removed private $rank everything worked as expected.

GWT - setText and setValue not working for TextBox on initial load

I have a couple of text-boxes on a page where the user can enter some numeric values; however, try as I might, I can't fill those text-boxes with default values - specifically I would like 0.0 displayed in both upon page load.
Here is how I create them and what I have tried -
GroupSection engineering_group = new GroupSection();
KSTextBox engrDesignTextBox = new KSTextBox();
engrDesignTextBox.setWidth("2.875em");
//engrDesignTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrDesignTextBox.setText("0.0"); ==> this doesn't work
engrDesignTextBox.setValue("0.0"); // doesn't work either
KSTextBox engrScienceTextBox = new KSTextBox();
engrScienceTextBox.setWidth("2.875em");
//engrScienceTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrScienceTextBox.setText("0.0"); ==> this doesn't work
engrScienceTextBox.setValue("0.0"); // doesn't work either
I'm thinking that I need to attach an "onload" event listener and then try the setText in there? That seems overkill for something that should be rather simple.
Incidentally, I have attached onBlurHandlers for both these text boxes and they work as expected (see code below)
The following code will simply insert0.0 if the user clicks or tabs out of the text-box while it is EMPTY.
engrDesignTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
engrScienceTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
EDIT : As requested here is how I have defined the setText and setValue methods in KSTextBox
public class KSTextBox extends TextBox implements HasWatermark {
.
.
.
#Override
public void setText(String text) {
String oldValue = super.getText();
if(hasWatermark) {
if(text == null || (text != null && text.isEmpty())){
super.setText(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setText(text);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setText(text);
}
ValueChangeEvent.fireIfNotEqual(this, oldValue, text);
}
#Override
public void setValue(String value) {
if(hasWatermark) {
if(value == null || (value != null && value.isEmpty())){
super.setValue(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setValue(value);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setValue(value);
}
}
So, getting back to the original question, how I do I initially set the values for these textboxes to 0.0?
That should have worked.Its very suprising. Is there a possibility that some other code is resetting the value after you did a setText or a setValue? Try debugging it in hosted mode.Put a breakpoint in setText and see when and how many times it is getting invoked

how can i show custom exception next to textbox?

I have register form. I want to check new username that is in db or not and if there is in DB , exception show next to it's textbox "UserName already exist...", what should I do?
this my method with exception that I have used it in Register action.:
public void InsertNewUser(MemberRegisterModel mm)
{
EShopThemeDBEntities context = new EShopThemeDBEntities(idbconnection.ConnStr);
using (context)
{
var listUsers = (from o in context.Users
select o.Username).ToList();
var a = listUsers.Count();
foreach (var item in listUsers)
{
if (mm.Username == item.ToString())
{
throw new Exception("UserName already exist...");
}
User mmr = new User();
mmr.FName = mm.FName;
mmr.LName = mm.LName;
mmr.Username = mm.Username;
mmr.Password = mm.Password;
mmr.Email = mm.Email;
mmr.Phone = mm.Phone;
mmr.Mobile = mm.Mobile;
mmr.CreateDate = DateTime.Now;
mmr.RoleId = 2;
context.AddToUsers(mmr);
context.SaveChanges();
}
}
You can set the Model error and return the model object back to view.
if(mm.Username == item.ToString())
{
ModelState.AddModelError("UserName","Username already taken";)
return View(model);
}
Also You do not need to get a list of usrs from database and do a loop to check whether the user entered user name exist or not. You can use the FirstOrDefault method to atleast one is there.
using (context)
{
var user=(from o in context.Users
where o.UserName==mm.UserName).FirstOrDefault();
if(user!=null)
{
ModelState.AddModelError("UserName","Username already taken";)
return View(model);
}
else
{
//Save new user info
}
}
Make sure you have the validation fields in your view, adjacent to the text box
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
But, Ideally, I would also do it asynchronosly with ajax to provide a rich user experience to the user. For that what you have to do is to look for the blur event of the text box and get the value of the textbox, make an ajax call to an action method which checks the availability of user name and return appropriate result.
<script type="text/javascript">
$(function(){
$("#UserName").blur(){
var userName=$(this).val();
$.getJSON("#Url.Action("Check","User")/"+userName,function(response){
if(response.status=="Available")
{
//It is available to register. May be show a green signal in UI
}
else
{
//not available. Show the message to user
$("#someMsgDIv").html("User name not available");
}
});
});
});
</script>
Now we should have an action method called Check in UserController to handle the ajax request
public ActionResult Check(string id)
{
bool isAvailable=false;
string userName=id;
//Check the user name is availabe here
if(isAvailable)
return Json(new { status="Available"},
JsonRequestBehaviour.AllowGet);
else
return Json(new { status="Not Available"},
JsonRequestBehaviour.AllowGet);
}
Note: Never do the client side approach only. Always do the server side checking no matter whether you have client side checking or not.
Shyju's answer is a thorough answer. However, based on your comments about handling the exception, here's a sample:
public void InsertNewUser(MemberRegisterModel mm)
{
// Some code...
if (userExists)
{
throw new ArgumentException("User name not available");
}
}
in your action method:
public ActionResult AddUser(MemberRegisterModel newUser)
{
try
{
var userManager = new MembersSrv();
userManager.InsertNewUser(newUser);
}
catch (ArgumentException ex)
{
if (ex.Message == "User name not available")
{
ModelState.AddModelError("UserName","Username already taken";)
return View(model);
}
}
}
Please note that the better way is to define a class which derives from Exception class (e.g. DuplicateUserNameException) and throw/catch that exception in your code. This sample code has been simplified.

Saving a custom object using IsloatedStorageSettings

I'm trying to save an object in IsolatedStorageSettings to save the high scores for my game, but whenever I try to save an updated copy of the object C# seems to think the object hasn't changed. I tried creating a custom Equals function for the HighScores class but that doesn't seem to help.
Any idea what I'm doing wrong?
Thanks
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (isolatedStore.Contains(Key))
{
// If the value has changed
if (isolatedStore[Key] != value) //This keeps returning false
{
// Store the new value
isolatedStore[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
isolatedStore.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
//This is located inside the HighScores class
public bool Equals(HighScores newHighScores)
{
for (int i = 0; i < highScores.Length; i++)
{
if (!highScores[i].Name.Equals(newHighScores.GetIndex(i).Name))
{
return false;
}
if (!highScores[i].Time.Equals(newHighScores.GetIndex(i).Time))
{
return false;
}
}
return true;
}
You haven't implemented the equality operators '==' and '!=' and these compare reference equality, you are going to have provide the implementation which maps on to your 'Equals' method
http://msdn.microsoft.com/en-us/library/ms173147%28v=vs.80%29.aspx
You should do isolatedStore.Save() to commit the changes

Resources