WPF TextBox 正则验证 大于等于0 小于等于1 的两位小数
正则:^(0\.\d+|[1-9][0-9]|1)$
textbox绑定正则验证
<textbox x:name="txb" maxlength="6" margin="1 0 0 0" width="40" >
<textbox.text>
<binding path="opacity" validatesonexceptions="true" validatesondataerrors="true" stringformat="f2"
mode="twoway" updatesourcetrigger="propertychanged" >
<binding.validationrules>
<shared1:inventoryvalidationrule inventorypattern="^(0\.\d+|[1-9][0-9]|1)$"/>
</binding.validationrules>
</binding>
</textbox.text>
</textbox>
用到的inventoryvalidationrule类:
public class inventoryvalidationrule : validationrule
{
#region properties
public string inventorypattern { get; set; }
#endregion properties
#region methods
public override validationresult validate(
object value, cultureinfo cultureinfo)
{
if (inventorypattern == null)
return validationresult.validresult;
if (!(value is string))
return new validationresult(false,
"inventory should be a comma separated list of model numbers as a string");
string[] pieces = value.tostring().split(',');
regex m_regex = new regex(inventorypattern);
foreach (string item in pieces)
{
match match = m_regex.match(item);
if (match == null || match == match.empty)
return new validationresult(
false, "invalid input format");
}
return validationresult.validresult;
}
#endregion methods
}