1

I'm trying to use regExp to validate an input.

The input should have a numeric field, with not more than 3 digits before the comma and not more than 2 digits after the comma.

I tried this regexp : [0-9]{1,3}([.|,][0-9]{1,2})?

But it does not work. The value 1234.567 is validated as ok although it should not.

Here the code i used to try this :

<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<script src="js/test.js"></script>
</head>
<body>

<input id="regExp1" type="text" value = "[0-9]{1,3}([\.|,][0-9]{1,2})?" />
<input type="button" value="->" onclick="applyRegExp(regExp1,test1)"> 
<input id="test1" type="text" />
<input type="button" onclick="TestRegExp(test1,test1Result)" value="test"> 
<div id="test1Result" ></div>

</body>
</html>

///.. test.js :
function applyRegExp(input1,input2){

    input2.pattern = input1.value;
}



    function TestRegExp( inputField,resultField){

        var regexp = new RegExp(inputField.pattern);
        var value = inputField.value;

        if (regexp.test(value)){
            resultField.innerHTML = inputField.name + " ok";
        }else
        {
            resultField.innerHTML = inputField.name + " not ok";
        }

    }

2 Answers 2

1

This might be what you want

^\d{1,3}([.|,]\d{1,2})?$

UPDATE: We just check for the string to match from the beginning to the end (with ^ and $)

. What is going on is just we allow 3 digits in a row (any), accept a dot or a comma but excpect with it at least 1 digit and at most 2.

Sign up to request clarification or add additional context in comments.

1 Comment

A little explanation would help.
1

Try this

^\d{1,3}([.|,]\d{1,2})?$

Regular expression visualization

2 Comments

This expects a float only
@aduch, Didnt notice the quantifier in quesn , Thanks :)

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.