i have form for customer data and i want to check if phone is exist in database(for both phone and phone 2) and even check for phone2. and if user write the same phone in both field not accepting.
here is my validation code:-
if($request->customer_id == null) {
unset($rules['customer_id']);
$rules['customer_name'] = 'required';
$rules['customer_address'] = 'required';
$rules['customer_phone'] = 'max:11|required|unique:customers,phone,phone2';
$rules['customer_phone2'] = 'max:11|unique:customers,phone,phone2';
$rules['customer_type'] = 'in:regular,special,jomla';
$mesages['customer_name.required'] = translate('the name is required');
$mesages['customer_address.required'] = translate('the address is required');
$mesages['customer_phone.required'] =translate('the phone is required');
$mesages['customer_phone.max'] =translate('the phone number is not correct');
$mesages['customer_phone.unique'] =translate('the phone number is used');
$mesages['customer_phone2.max'] =translate('the phone number is not correct');
$mesages['customer_phone2.unique'] =translate('the phone number is used');
you can try this
$rules['customer_phone'] = 'required|max:11|unique:customers,phone|unique:customers,phone2';
$rules['customer_phone2'] = 'required|max:11|unique:customers,phone|unique:customers,phone2|different:customer_phone';
The different rule ensures the phone and phone2 fields contain different values.
Related
I am trying to implement a check that gives the user an option to update the value of a specific slot within an intent after user Denies at confirmIntent step.
I have a newUser intent that has the following slots:
The updateNewUser is a custom slot type (expand values) with following entries:
Now, when a user Denies at confirmIntent step, I ask the user the slot which he/she wants to update/change, and store the user input value in updateNewUser slot using Lambda function elicitSlot. But here comes the problem.
Bot plays confirmation prompt with all captured values
User says "No" at confirmIntent
Bot elicits the updateNewUser slot by asking "What value do you
want to update?"
If user says a word that is an exact match of the entries of
updateNewUser custom slot type, then it works fine
If user says a similar (not exact match) word, like "name" or "email"
or "number", no value is stored inside updateNewUser and the bot
continues to confimation prompt.
Following is my Lambda code:
def newUser(intent_request):
slot_details = intent_request['currentIntent']['slotDetails']
slots = intent_request['currentIntent']['slots']
f_name = slots['f_name']
l_name = slots['l_name']
cellNum = slots['cellNum']
emailAdd = slots['emailAdd']
updateSlot = slots['updateNewUser']
session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
confirmation_status = intent_request['currentIntent']['confirmationStatus']
if intent_request['invocationSource'] == 'DialogCodeHook':
validation_result = validate_newusr(intent_request['currentIntent']['slots'], intent_request['currentIntent']['slotDetails'])
if not validation_result['isValid']:
slots = intent_request['currentIntent']['slots']
slots[validation_result['violatedSlot']] = None
slots['updateNewUser'] = None
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message']
)
if confirmation_status == 'Denied':
slots = intent_request['currentIntent']['slots']
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
slots,
'updateNewUser',
{
'contentType': 'SSML',
'content': '<speak>Which value do you want to change?</speak>'
}
)
return delegate(
session_attributes,
intent_request['currentIntent']['slots']
)
return close(
session_attributes,
'Fulfilled',
{
'contentType': 'SSML',
'content': '<speak>Your account has been created, and you will shortly receive an email to set up your password. Now, would you like to make a reservation for yourself, or for somone else?</speak>'
}
)
And following is the validation code:
def validate_newusr(slots, slot_details):
f_name = slots['f_name']
l_name = slots['l_name']
cellNum = slots['cellNum']
emailAdd = slots['emailAdd']
updateSlot = slots['updateNewUser']
if f_name:
if ' ' in f_name:
f_name = f_name.replace(' ', '')
slots['f_name'] = f_name
if l_name:
if ' ' in l_name:
l_name = l_name.replace(' ', '')
slots['l_name'] = l_name
if cellNum and (len(cellNum) != 10):
return build_validation_result(
False,
'cellNum',
'<speak>Please provide a valid, 10 digit phone number.</speak>'
)
return build_validation_result( #I use this to check whether updateNewUser stores something or not. But of course I only paste this code here at confirmIntent step; not before.
False,
'updateNewUser',
str(updateSlot)
)
if updateSlot: # this code won't run because updateSlot is empty
return build_validation_result(
False,
'updateNewUser',
str(updateSlot)
)
if len(slot_details['updateNewUser']['resolutions']) == 1 and str(list(slot_details['updateNewUser']['resolutions'][0].values())[0]).lower() in ['last name','first name', 'cell phone number', 'email address']:
slots['updateNewUser'] = list(slot_details['updateNewUser']['resolutions'][0].values())[0]
if len(slot_details['updateNewUser']['resolutions']) == 0 or str(list(slot_details['updateNewUser']['resolutions'][0].values())[0]).lower() not in ['last name','first name', 'cell phone number', 'email address']:
return build_validation_result(
False,
'updateNewUser',
'<speak>Sorry, I could not understand. Please say first name, last name, phone number, or email address.</speak>'
)
if slots['updateNewUser'] == 'first name':
return build_validation_result(
False,
'f_name',
'<speak>Please say your updated first name.</speak>'
)
if slots['updateNewUser'] == 'last name':
return build_validation_result(
False,
'l_name',
'<speak>Please say your updated last name.</speak>'
)
if slots['updateNewUser'] == 'cell phone number':
return build_validation_result(
False,
'cellNum',
'<speak>Please say, or type your updated phone number.</speak>'
)
if slots['updateNewUser'] == 'email address':
return build_validation_result(
False,
'emailAdd',
'<speak>Please say your updated email address.</speak>'
)
return {'isValid': True}
Here are some screenshots of the chat:
User declines at confirmIntent, bot asks which value to update:
User says "name", bot jumps to confirmation prompt
If exact matching word is provided to Lex, it accepts it:
Returning what value bot stored in updateNewUser in case of "name" as input:
Another example:
It only accepts exact match in my case. But if I make updateNewUser slot as mandatory/required, it starts to accept similar words too and works fine. But I need this slot as optional. My goal is to update a single slot instead of repeating the whole intent. What am I doing wrong?
At first glance, I would suggest changing the resolution of the updateNewUser slot type to restricted values and synonyms. That will enable you to add synonyms that match with your base value.
Ensure that your valueSelectionStrategy is TOP_RESOLUTION so that you get the base value rather than the user's raw input.
This simplifies your lambda as you would only need to cater for a single value per line.
Custom Slot Types
I'm trying to update a record given the customer Id, the row Id, and a dynamic column name.
Thus far I have the following, with the trouble spot marked by ***:
public void UpdateRecord(int Id, string rval, string column, string value)
{
var rId = GetRvalId(rval);
var entry = _context.Customers
.Where(x => x.Id == Id && x.RVals.Id == rId && x.***column?*** == column).First();
entry = value;
}
I haven't been able to find a good example of how to do this.
Addition after comments at the end
The reason you couldn't find examples is because it is not a good design.
Your method is very error prone, difficult to test and horrible to maintain. What if someone types the incorrect column name? What if you try to assign a string to the customer's birthday? And even if you would implement some string checking for column names and proposed values, then your program wouldn't work anymore after someone changes the names or the types of the columns.
So let's redesign!
Apparently you have a Customer with an Id and a property Rvals. This property Rvals also has a property Id.
You also have a function GetRValId that can convert a string rval to an int rvalId.
What you want, is given an Id and a string rval, you want to update one of the columns of the first Customer with this Idand rValId.
Side questions: Can there be more than one Customer with Id? In that case: are you sure Id is an ID? What do you want if there are more matching Customers? Update all customers or update only the first one? Which customer do you define as the first customer?
Leaving the side questions aside. We want a function signature that reports errors at compile time if you use non-existing customer properties, or if you try to assign a string to a Birthday. Something like this perhaps?
Update the name of the customer:
int customerId = ...
string rval = ...
string proposedName = "John Doe";
UpdateCustomerRecord(id, rval, customer => customer.Name = proposedName);
Update the Birthday of the customer:
DateTime proposedBirthday = ...
UpdateCustomerRecord(id, rval, customer => customer.Birthday = proposedBirthday)
This way you can't use any column that does not exist, and you can't assign a string to a DateTime.
You want to change two values in one call? Go ahead:
UpdateCustomerRecord(id, rval, customer =>
{
customer.Name = ...;
customer.Birthday = ...;
});
Convinced? Let's write the function:
public void UpdateCustomerRecord(int customerId, string rval, Action<Customer> action)
{
// the beginning is as in your function:
var rId = GetRvalId(rval);
// get the customer that you want to update:
using (var _Context = ...)
{
// get the customer you want to update:
var customerToUpdate = _Context.Customers
.Where(customer => customer.Id == Id
&& customer.RVals.Id == rId)
.FirstOrDefault();
// TODO: exception if there is no customerToUpdate
// perform the action and save the changes
action(customerToUpdate);
_context.SaveChanges();
}
Simple comme bonjour!
Addition after comments
So what does this function do? As long as you don't call it, it does nothing. But when you call it, it fetches a customer, performs the Action on the Customer you provided in the call, and finally calls SaveChanges.
It doesn't do this with every Customer, no it does this only with the Customer with Id equal to the provided Id and customer.RVals.Id == ... (are you still certain there is more than one customer with this Id? If there is only one, why check for RVals.Id?)
So the caller not only has to provide the Id, and the RVal, which define the Customer to update, but he also has to define what must be done with this customer.
This definition takes the form of:
customer =>
{
customer.Name = X;
customer.BirthDay = Y;
}
Well if you want, you can use other identifiers than customer, but it means the same:
x => {x.Name = X; x.BirthDay = Y;}
Because you put it on the place of the Action parameter in the call to UpdateCustomerRecord, I know that x is of type Customer.
The Acton statement means: given a customer that must be updated, what must we do with the customer? You can read it as if it was a Function:
void Action(Customer customer)
{
customer.Name = ...
customer.BirthDay = ...
}
In the end it will do something like:
Customer customerToUpdate = ...
customerToUpdate.Name = X;
customerToUpdate.BirthDay = Y;
SaveChanges();
So in the third parameter, called Action you can type anything you want, even call functions that have nothing to do with Customers (probably not wise). You have an input parameter of which you are certain that it is a Customer.
See my earlier examples of calling UpdateCustomerRecord, one final example:
UpdateCustomerRecord( GetCustomerId(), GetCustomerRVal,
// 3rd parameter: the actions to perform once we got the customerToUpdate:
customer =>
{
DateTime minDate = GetEarliestBirthDay();
if (customer.BirthDay < minDate)
{ // this Customer is old
customer.DoThingsThatOldPeopleDo();
}
else
{ // this Customer is young
customer.DoThingsThatYoungPeopleDo();
}
}
}
So the Action parameter is just a simpler way to say: "once you've got the Customer that must be updated, please perform this function with the Customer
So if you only want to update a given property of the customer write something like:
UpdateCustomerRecord(... , customer =>
{
Customer.PropertyThatMustBeUpdated = NewValueOfProperty;
}
Of course this only works if you know which property must be updated. But since you wrote "I am trying to update a specific cell." I assume you know which property the cells in this column represent.
It is not possible to pass the column name as the string value in LINQ. Alternate way to do it, if you have the limited number of the column name which can be passed then it can be achieved as below:
public void UpdateRecord(int Id, string rval, string column, string value)
{
var rId = GetRvalId(rval);
var entry = _context.Customers
.Where(x => x.Id == Id &&
x.RVals.Id == rId &&
(x.column1 == value || column == column1) &&
(x.column2 == value || column == column2) &&
(x.column3 == value || column == column3) &&
(x.column4 == value || column == column4) &&
(x.column5 == value || column == column5) &&
)).First();
entry = value;
}
UpdateRecord(5, "rval", "column1", "value");
UpdateRecord(5, "rval", "column2", "value");
UpdateRecord(5, "rval", "column3", "value");
Here, suppose you have the 5 columns that can be passed while calling the funcion UpdateRecord then you can add the 5 clauses in the WHERE as above.
Other way to do it dynamic LINQ
var entry = db.Customers.Where(column + " = " + value).Select(...);
Platform : Domino v9
Background:
When an user opens a document using an Xpage, the Rich Text control (CKEditor)displays the existing content in that document.
The RichText field is bound to a backend Notes document.
When an user makes any changes to this content and clicks the Update button, validation occurs (for this example, we are checking to see if length exceeds 20 characters).
Validation is done using the ValidateExpression option.
On validation, user sees the error message but the new content entered by user is lost. The Rich Text control displays the original content.
Validation Code
<xp:this.validators>
<xp:validateExpression>
<xp:this.expression><![CDATA[#{javascript:var contentStr = value.getContentAsText();
var regex = /(<([^>]+)>)/ig ;
contentStr = contentStr.replace(regex,'');
if( contentStr.length < 20 ) {
return true;
}else{
return false;
}
}]]></xp:this.expression>
<xp:this.message><![CDATA[#{javascript:var errMsg = getErrorMessageText ('713','');
if ( errMsg != null && errMsg != "") {
//return errMsg;
return "Length cannot exceed 20 characters";
}else{
return "Length cannot exceed 20 characters";
}}]]></xp:this.message>
</xp:validateExpression>
</xp:this.validators>
Things I tried:
I tried the solution mentioned in Tommy Valand's blog but that did not solve the problem. Tommy's Blog
Question
How do I validate the RichText control without losing the new content ?
Screenshots:
When I have complex validation, I sometimes use a hidden input field for validation. Not sure if this will help in this situation, but could be worth a try..
getLocalValue should return the converted value in the validation phase. Since you're dealing with strings, getSubmittedValue might be even more appropriate/easier to use.
If you use xp:message, set the for attribute to whatever id you decide for the hidden field.
<xp:inputHidden id="dummyValidatorField" value="dummyValue">
<xp:this.validators>
<xp:validateExpression>
<xp:this.expression><![CDATA[#{javascript:var contentStr = getComponent( 'idOfRtField' ).getLocalValue(); // maybe you need to append .getContentAsText();
var regex = /(<([^>]+)>)/ig ;
contentStr = contentStr.replace(regex,'');
if( contentStr.length < 20 ) {
return true;
}else{
return false;
}
}]]></xp:this.expression>
<xp:this.message><![CDATA[#{javascript:var errMsg = getErrorMessageText ('713','');
if ( errMsg != null && errMsg != "") {
//return errMsg;
return "Length cannot exceed 20 characters";
}else{
return "Length cannot exceed 20 characters";
}}]]></xp:this.message>
</xp:validateExpression>
</xp:this.validators>
Strange behavior. Maybe you can validate your RTF control via CSJS (and not SSJS/Java) with this recently added snippet: http://openntf.org/XSnippets.nsf/snippet.xsp?id=validate-rich-text-field
Is it possible from your Windows Phone 7/8 application to get access to the phone call feature? I.e. if I have a string that contains a phone number, I'd like to send the user straight to the "phone" app with the number ready.
If your string is a phone number, you can simply use the code below. If your string contains a phone number you first have to extract it.
I use a regex for that. You can use my code below but you might need to change something depending on the format of your strings:
public static String GetFirstPhoneNumber(String includesnumber)
{
MatchCollection ms = Regex.Matches(includesnumber, #"([0-9][^A-Z^a-z]+)([A-Za-z]|$)");
Regex digitsOnly = new Regex(#"[^\d]");
for (int i = 0; i < ms.Count; i++)
{
String res = digitsOnly.Replace(ms[i].Value, "");
if (res.Length > 5)
return res;
}
return "";
}
You can read more about that here: A comprehensive regex for phone number validation
Here the actual PhoneCallTask:
Microsoft.Phone.Tasks.PhoneCallTask t = new Microsoft.Phone.Tasks.PhoneCallTask();
t.PhoneNumber = numbertocall;
t.DisplayName = displayname;
t.Show();
Check out 'How to use the phone call task for Windows Phone' guide at the MSDN website, I believe that's what you're looking for.
I have the following LINQ query using EF5 and generic repository, unit of work patterns to a SQL Server 2008 db
var countriesArr = GetIdsFromDelimStr(countries);
var competitionsArr = GetIdsFromDelimStr(competitions);
var filterTeamName = string.Empty;
if (teamName != null)
{
filterTeamName = teamName.ToUpper();
}
using (var unitOfWork = new FootballUnitOfWork(ConnFooty))
{
// give us our selection of teams
var teams =
(from team in
unitOfWork.TeamRepository.Find()
where ((string.IsNullOrEmpty(filterTeamName) || team.Name.ToUpper().Contains(filterTeamName)) &&
(countriesArr.Contains(team.Venue.Country.Id) || countriesArr.Count() == 0))
select new
{
tId = team.Id
}).Distinct();
// give us our selection of contests
var conts = (
from cont in
unitOfWork.ContestRepository.Find(
c =>
((c.ContestType == ContestType.League && competitionsArr.Count() == 0) ||
(competitionsArr.Contains(c.Competition.Id) && competitionsArr.Count() == 0)))
select new
{
contId = cont.Id
}
).Distinct();
// get selection of home teams based on contest
var homecomps = (from fixt in unitOfWork.FixtureDetailsRepository.Find()
where
teams.Any(t => t.tId == fixt.HomeTeam.Id) &&
conts.Any(c => c.contId == fixt.Contest.Id)
select new
{
teamId = fixt.HomeTeam.Id,
teamName = fixt.HomeTeam.Name,
countryId = fixt.HomeTeam.Venue.Country.Id != null ? fixt.HomeTeam.Venue.Country.Id : 0,
countryName = fixt.HomeTeam.Venue.Country.Id != null ? fixt.HomeTeam.Venue.Country.Name : string.Empty,
compId = fixt.Contest.Competition.Id,
compDesc = fixt.Contest.Competition.Description
}).Distinct();
// get selection of away teams based on contest
var awaycomps = (from fixt in unitOfWork.FixtureDetailsRepository.Find()
where
teams.Any(t => t.tId == fixt.AwayTeam.Id) &&
conts.Any(c => c.contId == fixt.Contest.Id)
select new
{
teamId = fixt.AwayTeam.Id,
teamName = fixt.AwayTeam.Name,
countryId = fixt.AwayTeam.Venue.Country.Id != null ? fixt.AwayTeam.Venue.Country.Id : 0,
countryName = fixt.AwayTeam.Venue.Country.Id != null ? fixt.AwayTeam.Venue.Country.Name : string.Empty,
compId = fixt.Contest.Competition.Id,
compDesc = fixt.Contest.Competition.Description
}).Distinct();
// ensure that we return the max competition based on id for home teams
var homemax = (from t in homecomps
group t by t.teamId
into grp
let maxcomp = grp.Max(g => g.compId)
from g in grp
where g.compId == maxcomp
select g).Distinct();
// ensure that we return the max competition based on id for away teams
var awaymax = (from t in awaycomps
group t by t.teamId
into grp
let maxcomp = grp.Max(g => g.compId)
from g in grp
where g.compId == maxcomp
select g).Distinct();
var filteredteams = homemax.Union(awaymax).OrderBy(t => t.teamName).AsQueryable();
As you can see we want to return the following format which is passed across to a WebAPI so we cast the results to types we can relate to in the UI.
Essentially what we are trying to do is get the home and away teams from a fixture, these fixtures have a contest which relates to a competition. We then get the highest competition id from the grouping and then this is returned with that team. The country is related to the team based on the venue id, when I was originally doing this i had problems figuring out how to do OR joins in linq which is why i split it down to getting home teams and away team and then grouping them based on competition then unioning them together.
An idea of current table size is fixtures has 7840 rows, teams has 8581 rows, contests has 337 rows and competitions has 96 rows. The table that is likely to increase rapidly is the fixture table as this is related to football.
The output we want to end up with is
Team Id, Team Name, Country Id, Country Name, Competition Id, Competition Name
Using no filtering this query takes on average around 5 secs, just wondering if anybody has any ideas/pointers on how to make it quicker.
thanks in advance Mark
I can't judge whether it will speed up things, but your homemax and awaymax queries could be
var homemax = from t in homecomps
group t by t.teamId into grp
select grp.OrderByDescending(x => x.compId).FirstOrDefault();
var awaymax = from t in awaycomps
group t by t.teamId into grp
select grp.OrderByDescending(x => x.compId).FirstOrDefault();
Further, as you are composing one very large query it may perform better when you cut it up in a few smaller queries that fetch intermediary results. Sometimes a few more roundtrips to the database perform better than one very large query for which the database engine can't find a good execution plan.
Another thing is all these Distinct()s. Do you always need them? I think you can do without because you are always fetching data from one table without joining a child collection. Removing them may save a bunch.
Yet another optimization could be to remove the ToUpper. The comparison is done by the database engine in SQL and chances are that the database has a case-insensitive collation. If so, the comparison is never case sensitive even if you'd want it to be! Constructs like Name.ToUpper cancel the use of any index on Name (it is not sargable).