Click here to Skip to main content
15,907,183 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hi
I need to validate a string against the entered string.
eg:
string to be validated is "hello"

if i enter hullo,it should return false

thanks
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jun-12 21:32pm    
You need to tag application type or UI library to be used, as soon as this is related to UI. Please see the explanation in the answer by VJ Reddy.
--SA

The question is not tagged with UI type WindowsForms, WPF, ASP.NET etc. and it is not mentioned which control is to be validated.

In WindowsForms the Validating event of the Control can be used to test for a condition and if the condition is not satisfied then the System.ComponentModel.CancelEventArgs argment property Cancel can be set to true to retain focus in the Control till the condition is satisified.

If a TextBox is to be validated in WindowsForms then the following code can be used
C#
textBox1.Validating += (sender, args) => {
    if(!textBox1.Text.Equals("hello", StringComparison.InvariantCulture))
        args.Cancel=true;
};

If the purpose is only to a have function to check for the condition then the following method using string.Equals method can be used as it offers StringComparison.InvariantCulture option.
C#
public bool IsValid(string stringToTest){
   return stringToTest.Equals("hello",StringComparison.InvariantCulture);
};
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Jun-12 21:31pm    
Good point, and correct code; appreciate using anonymous + lambda. My 5.
--SA
VJ Reddy 7-Jun-12 23:03pm    
Thank you very much, SA :)
codeBegin 8-Jun-12 2:20am    
good one 5!
VJ Reddy 8-Jun-12 2:58am    
Thank you, codeBegin :)
C#
bool validate(String str)
{
   bool rv=false;
   if(str=="hello")
   {
      rv=true;
   }
   return rv;
}
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 7-Jun-12 21:36pm    
A vote of 1:
If you decided to write trivial thing (I doubt OP would need it), you could at least write without all that foolishness:

bool validate(string value) {
return value == "hello";
}


In this case, writing more than one line is nearly a crime. Your vote of 1 is well deserved.

Please also keep in mind that you should only answer question on the matter you know really well. Bad answers in more harm than help and much worse than not answering at all. Please be responsible.

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900