[DataType(DataType.PhoneNumber)]
[RegularExpression("^([0-9 .()-+)$", ErrorMessage = CommonConstants.PhoneError)]
public string PhoneNumber { get; set; }
I have a PhoneNumber field. With this field I want to give a permission for user, just type number or +,-,),(.
How can I have a RegularExpression ?
Your current regex has an unterminated character group ([ with no ]). You want something like this:
^([\d() +-]+)$
Note the order of + and - - - is a range indicator, so it needs to be first, last, or escaped (as in \-).
Here's a demo.
Related
How can i outputs result between 2 specific characters in dart String
example
String myVlue = 'helloWorld';
wanted result is : anything between 'hel' and 'ld'
so the result is 'loWor'
Note : in my case the two specific characters are fixed and Unique
How can i tell dart to do that in best way .
thanks
You could define a regular expression to catch a group from your input:
void main() {
String myValue = 'helloWorld';
RegExp regExp = RegExp(r'hel(.*)ld');
String extract = regExp.firstMatch(myValue)![1]!;
print(extract); // loWor
}
I have a customer form having phone number fields like CountryCode, AreaCode and PhoneNumber. I would like to write a custom validation for these 3 fields where all of them can either remain empty (they are optional) or all of them can remain filled (no field can be left empty if one or two are filled).
Am trying to write a custom validation for this situation, however, am not clear how to do it. Please help.
It's unclear exactly what you're looking for here. If you're just struggling with the boolean logic, all you need is:
if (!String.IsNullOrWhiteSpace(model.CountryCode) ||
!String.IsNullOrWhiteSpace(model.AreaCode) ||
!String.IsNullOrWhiteSpace(model.PhoneNumber))
{
if (String.IsNullOrWhiteSpace(model.CountryCode)
{
ModelState.AddModelError(nameof(model.CountryCode), "Country code is required.");
}
if (String.IsNullOrWhiteSpace(model.AreaCode)
{
ModelState.AddModelError(nameof(model.AreaCode), "Area code is required.");
}
if (String.IsNullOrWhiteSpace(model.PhoneNumber)
{
ModelState.AddModelError(nameof(model.PhoneNumber), "Phone number is required.");
}
}
Essentially, you just first check to see if any of them have a value. Then, you individually add an error for each one that does not have a value.
That said, these broken out phone number fields are atrocious. I'm not sure where the idea came from, but it's like you just can't get people off of them now. Phone number formats vary wildly, and not every phone number actually has an "area code". It's far better to have a single "phone" field where the user can simply type their entire phone number. Then, you can use something like this port of Google's libphonenumber library to validate the number and format it into a standard form. You can even use the library to parse out the individual pieces of country code, area code, and number, if you need to store it like this. Just be prepared that the area code may not have a value and even if it does, it may not be exactly 3 digits. Same goes for number portion, as well: you can't assume it will always be 7.
Validate a phone number
var phoneUtil = PhoneNumberUtil.GetInstance();
try {
var phoneNumber = phoneUtil.Parse(model.Phone, countryISO2);
if (!phoneUtil.IsValidNumber(phoneNumber))
{
ModelState.AddModelError(nameof(model.Phone), "Invalid phone number.");
}
} catch (NumberParseException) {
ModelState.AddModelError(nameof(model.Phone), "Invalid phone number.");
}
Where countryISO2 is the two character country code: "US", "GB", etc. If you want to accept international phone numbers, you should collect the country from the user.
Format a phone number
phoneUtil.Format(phoneNumber, PhoneNumberFormat.NATIONAL);
Get component parts of a phone number
var countryCode = phoneNumber.CountryCode;
string areaCode;
string number;
var nationalSignificantNumber = phoneUtil.GetNationalSignificantNumber(phoneNumber);
var areaCodeLength = phoneUtil.GetLengthOfGeographicalAreaCode(phoneNumber);
if (areaCodeLength > 0) {
areaCode = nationalSignificantNumber.Substring(0, areaCodeLength);
number = nationalSignificantNumber.Substring(areaCodeLength);
} else {
areaCode = "";
number = nationalSignificantNumber;
}
it is my first time to use elasticsearch Grails plugin in my Grails2.5.1application , when i'm trying to search for age=35 using elasticSearchService.search("${age:35}").searchResults or using domainName.search("${age:35}").searchResults the searchresults is empty although there is a record in the DB age is equal to 35. And is there any useful tutorial for using ElasticSearch with Grails.
here is my domain:
class EmploymentSeeker {
String empType
String email
String fullName
String expYears
String socialStatus
Integer nubOfKids =0
String computerKnowledge
String militaryStatus
String haveDrivingLic
String gender
String eduQualification
String hasVehicle
String placeOfStudying
String courses
String currentTitle
String currentEmployerName
Integer age
Date dateCreated
static searchable = {
age boost:2.0
root true
except = ['email', 'fullName', 'placeOfStudying', 'currentTitle', 'currentEmployerName', 'dateCreated']
}
static constraints = {
}
static mapping={
}
}
Looks like you have a rogue '$' in your query string. It probably should be:
elasticSearchService.search("age:35")
${..} is needed only if you are passing in a query and want Groovy to replace the expression before invoking the ElasticSearchService.
I need to control a field with a min length if someone enters a value but if they don't enter anything in, I don't want the form to tell them there is a min value.
This is what I have:
[Required]
[StringLength(15, ErrorMessage = "Please supply at least {2} characters.", MinimumLength = 3)]
[Display(Name = "Last name on account or first part of the company's name")]
public string LastName { get; set; }
I just need for it to allow blanks also or if data is entered, require it to be a min of 3 characters..
Any suggestions?
The problem is with the validation logic of the StringLength attribute, that returns true also for the string with null value, here the implementation:
public override bool IsValid(object value)
{
this.EnsureLegalLengths();
int num = value == null ? 0 : ((string) value).Length;
if (value == null)
return true;
if (num >= this.MinimumLength)
return num <= this.MaximumLength;
else
return false;
}
Also the Required attribute that you used is not helping :-).
Anyway the only thing you can do for your scenario is to create a custom attribute to validate LastName with the logic that you need, here a link to an MVC3 example, or you can try googling, there is a lot of examples and is not hard to implement.
Is it possible to both validate, that the provided data is in the form of a phone number AND trim it down to just the numbers in the validator?
Input: (902) 837-2832
Output: VALID: YES, 9028372832
Or do I have to convert the input to the number-only format after the fact?
Add a property to your model with only a getter that returns the stripped down version of the property that is bound to the input. Put your validation attribute on that property.
public string PhoneNumber {get;set;}
[Required(ErrorMessage="Phone number is required.")]
[RegularExpression(#"\d{10}", ErrorMessage="Phone number is invalid.")]
public string PhoneNumberValue
{
get
{
var temp = PhoneNumber
temp = Regex.Replace(temp, #"[^0-9]", "");
temp = temp.Length == 11 && temp.StartsWith("1")
? temp.Substring(1) : temp;
}
set
{
// I can't remember off the top of my head if MVC model
// binding requires a setter or not. If so, just leave this
// empty. Otherwise you can remove it entirely.
}
}
Then, in your view, just render the alternate validation message.
#Html.LabelFor(x=>x.PhoneNumber)
#Html.TextBoxFor(x=>x.PhoneNumber)
#Html.ValidationMessageFor(x=>x.PhoneNumberValue)
Here is an example how to validate with Regular expression:
[Required(ErrorMessage="Phone Number is required")]
[RegularExpression("^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage="Not a valid number")]
public string PhoneNumber { get; set; }
We may use Trim method of string to clean the phone number and get only digits.
char[] charsToTrim = { '(', ' ', ')', '-'};
string phoneNumber = "(123)-345-6789";
string result = banner.Trim(charsToTrim);
Finally here is a post that explains Enabling Validation using DataAnnotations in more detail