1

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

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}))$/; Commented Oct 10, 2014 at 6:43

2 Answers 2

3

If 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply. I try like following but didn't work. var regExp = /^(([a-zA-Z]+)|(\d{0,15}\.\d{0,2}))$/; var res = regExp.test(extCost);
1

To avoid your problem use JavaScript syntax and as already mentioned you you should escape the decimal dot (\.) or use [\.,] to match a comma too (the given example will also match 123W4):

var regExp = /(([a-zA-Z]+)|(\d{0,15}\.\d{0,2}))/;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.