I have created a regular expression in C# that I am using in model validations. I need same in JavaScript. Please help me to convert.
Here is the regular expression in C#
[Required]
[Display(Name = "Cost")]
[DataType(DataType.Currency)]
[RegularExpression(@"^(([a-zA-Z]+)|(\d{0,15}.\d{0,2}))$", ErrorMessage = "Cost can not have more than 2 decimal places.")]
[Range(typeof(Decimal), "0.01", "99999999999999.99", ErrorMessage = "{0} must be a decimal/number greater than 0 and less than 100000000000000.")]
public Nullable<decimal> Cost { get; set; }
And one more validation message "Field must be a number"
I am trying like this in javascript
var regExp = new RegExp("(([a-zA-Z]+)|(\d{0,15}.\d{0,2}))");
var res = regExp.test($('#Cost').val());
But this always returns true
Thanks
I have created a regular expression in C# that I am using in model validations. I need same in JavaScript. Please help me to convert.
Here is the regular expression in C#
[Required]
[Display(Name = "Cost")]
[DataType(DataType.Currency)]
[RegularExpression(@"^(([a-zA-Z]+)|(\d{0,15}.\d{0,2}))$", ErrorMessage = "Cost can not have more than 2 decimal places.")]
[Range(typeof(Decimal), "0.01", "99999999999999.99", ErrorMessage = "{0} must be a decimal/number greater than 0 and less than 100000000000000.")]
public Nullable<decimal> Cost { get; set; }
And one more validation message "Field must be a number"
I am trying like this in javascript
var regExp = new RegExp("(([a-zA-Z]+)|(\d{0,15}.\d{0,2}))");
var res = regExp.test($('#Cost').val());
But this always returns true
Thanks
Share Improve this question edited Oct 10, 2014 at 6:42 Soner Gönül 99k103 gold badges222 silver badges373 bronze badges asked Oct 10, 2014 at 6:42 cachetcachet 3204 silver badges18 bronze badges 1-
I'd suggest using JavaScript's built-in regex syntax to avoid string escaping issues:
var regExp = /^(([a-zA-Z]+)|(\d{0,15}.\d{0,2}))$/;
– cdhowie Commented Oct 10, 2014 at 6:43
2 Answers
Reset to default 3If you're trying to verify that cost must contain 2 decimal places, then take out the "or" part in your regex that matches any alpha string:
^(\d{0,15}\.\d{0,2})$
Note: You also don't need parenthesis since you're not going to do anything with the captured value here.
The regex you mentioned will fail in C# as well, but you get the illusion of it working because of your Range
attribute.
And finally, if you're using new Regexp
syntax, you need to escape the slashes:
var re = new RegExp("^\\d{0,15}\\.\\d{0,2}$");
// or using shorter JS syntax
var re = /^\d{0,15}\.\d{0,2}$/;
Sample runs:
console.log(re.test("abc")); // false
console.log(re.test("10.23")); // true
console.log(re.test("10")); // false
To avoid your problem use JavaScript syntax and as already mentioned you you should escape the decimal dot (\.
) or use [\.,]
to match a ma too (the given example will also match 123W4
):
var regExp = /(([a-zA-Z]+)|(\d{0,15}\.\d{0,2}))/;