c# - String Needs to Contain 2 words -
i have textbox on 1 of views, , textbox should not accept has more 2 words or less 2 words. textbox needs 2 words.
basically textbox accepts person's first , last name. don't want people enter 1 or other.
is there way check space
character between 2 words , space
character along letter
, number
, etc after 2nd word if exists? think if user accidently 'fat-fingers' space after 2nd word, should fine bc there still 2 words.
for example:
/* _ character means space */ john /* not accepted */ john_ /* not accepted */ john_smith_a /* not accepted */ john smith_ /* accepted */
any appreciated.
there multiple approaches use solve this, i'll review on few.
using string.split()
method
you use string.split()
method break string it's individual components based on delimiter. in case, use space delimiter individual words :
// words, removing empty entries along way var words = yourtextbox.split(new char[] { ' ' }, stringsplitoptions.removeemptyentries); // determine how many words have here if(words.length != 2) { // tell user made horrible mistake not typing 2 words here }
using regular expression
additionally, attempt resolve via regular expression using regex.ismatch()
method :
// check 2 words (and allow beginning , trailing spaces) if(!regex.ismatch(input,@"^(\s+)?\w+\s+\w+(\s+)?")) { // there not 2 words, }
the expression may bit scary, can broken down follows :
^ # matches start of string (\s+)? # optionally allows single series of 1 or more whitespace characters \w+ # allows 1 or more "word" characters make first word \s+ # again allow series of whitespace characters, can drop + if want 1 \w+ # here's second word, nothing new here (\s+)? # allow trailing spaces (up if want them)
a "word" character \w
special character in regular expressions can represent digit, letter or underscore , equivalent of [a-za-z0-9_]
.
taking advantage of regular expressions using mvc's regularexpressionattribute
finally, since using mvc, take advantage of [regularexpressionvalidation]
attribute on model :
[regularexpression(@"^(\s+)?\w+\s+\w+(\s+)?", errormessage = "exactly 2 words required.")] public string yourproperty { get; set; }
this allow call modelstate.isvalid
within controller action see if model has errors or not :
// check validation attributes 1 mentioned above if(!modelstate.isvalid) { // have errors, not 2 words }
Comments
Post a Comment