Link to home
Start Free TrialLog in
Avatar of ksd123
ksd123

asked on

validation and formatting using custom directive with angularjs

I am writing custom directive to validate and format the input using angularjs and I stuck in the middle while formatting the input.The valid input must have 3 digits with 2 decimals.Below I have mentioned 3 regex patterns with output format and if user enters any one of the below matching regex pattern and it should format accordingly.
In the directive I am using blur function because I want format/show error message when user leaves the textbox.Please help me to fix this issue.Here is the fiddle.fiddle


            input with reg pattern             output(need to format)

      Ex:      // [/^\d{3}$/] 789  --->               789.00
              // [/^(\d{3})\.(\d{1})$/] 789.4  --->  789.40
                // [/^(\d{3})(\d{2})$/] 78945-->       789.45
Avatar of leakim971
leakim971
Flag of Guadeloupe image

why a regex?

if(inputvalue) {
   return ((inputvalue.substr(0,3) + "." + inputvalue.substr(3) ) * 1).toFixed(2);
}
return undefined;

Open in new window

Avatar of ksd123
ksd123

ASKER

Thank you.I have updated the directive with the above code.It is not working as expected,sometimes I am getting NaN ,if I enter 10 digits it's formatting and giving first 5 digits with 2 decimals which is not valid as it show error message.In  one scenario it is working as expected ie. if user enters 123, it gives 123.00.
Here is the updated fiddle directive.Can you correct me what went wrong?
Below is my requirement
Invalid input
12346789-invalid format
Qswe1234-invalid format

If user enters valid input then it should format
Valid input
123 ---> 123.00
123.4--->123.40
12345--->123.45
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ksd123

ASKER

Thank you so much,It's working fine in following scenarios
123 ---> 123.00
123.4--->123.40
12345--->123.45

But still it is failing in  following scenarios and want to show expected output (error message) for below scenarios.The valid input must have 3 digits with 2 decimals

i/p                actual o/p     expected o/p
123456-->        123.46             Invalid Format error message
1234567-->      123.46             Invalid Format error message
12            -->      12.00               Invalid Format error message
1              ->         1.00                Invalid Format error message
abcdef    -->     NaN                Invalid Format error message