c# - How to validate a string value that should only return true if numbers are entered -
c# - How to validate a string value that should only return true if numbers are entered -
i need extend code phone call getreasonforfailure method if other numbers returned.
i.e
123 = invalid
abc = invalid
1234567890 = isvalid
null = isvalid
using system.linq; namespace worksheetvalidator.rules { public class importcommoditycode : irule { public bool isvalid(string value) { homecoming string.isnullorempty(value) || value.length == 10 ; } public string getreasonforfailure(string value) { homecoming string.format("[{0}] codes should 10 digits long , contain numbers", value); } }
}
int32.tryparse cannot used in context because 9999999999
bigger int32.maxvalue overflows , conversion fails. utilize long.tryparse
or, if want ienumerable solution, write
public class importcommoditycode : irule { public bool isvalid(string value) { homecoming string.isnullorempty(value) || (value.length == 10 && !value.asenumerable().any (t => !char.isdigit(t))); } }
this code conforms requirement null (or empty) string should considered valid albeit bit perplexed condition. easy alter part using
homecoming !string.isnullorempty(value) && ....
c#
Comments
Post a Comment