验证输入的值是否正确 [英] Validate if the value entered is correct

查看:87
本文介绍了验证输入的值是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我需要针对输入的字符串验证字符串.
例如:
要验证的字符串是"hello"

如果我输入hullo,它应该返回false

谢谢

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

推荐答案

问题is not tagged with UI type WindowsForms, WPF, ASP.NET etc.并没有提到which control is to be validated.

WindowsForms 中,可以将Control Validating 事件用于测试条件,如果不满足条件,则可以将System.ComponentModel.CancelEventArgs argment属性Cancel 设置为true以在Control 直到条件得到满足.

如果要在WindowsForms 中验证TextBox ,则可以使用以下代码
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
textBox1.Validating += (sender, args) => {
    if(!textBox1.Text.Equals("hello", StringComparison.InvariantCulture))
        args.Cancel=true;
};


如果只是为了让function 检查条件,则可以使用以下使用string.Equals 方法的方法,因为它提供了StringComparison.InvariantCulture选项.


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.

public bool IsValid(string stringToTest){
   return stringToTest.Equals("hello",StringComparison.InvariantCulture);
};


bool validate(String str)
{
   bool rv=false;
   if(str=="hello")
   {
      rv=true;
   }
   return rv;
}


这篇关于验证输入的值是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆