Prevent invalid formats based on given regex - javascript

I have a regex for a set of use cases
Based on that regex I'm trying to prevent the user to type invalid formats.
The regex works and preventing the user adding invalid formats also works.
The part with which I'm struggling now is that if the default value is invalid, the user cannot add additional valid characters.
Here is what I have: http://jsfiddle.net/jgqco7by/2/.
<input id="myInput" type="text" value="co vi1d-" />
var previousValue = document.getElementById('myInput').value;
var pattern = /^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').oninput = validateInput;
In this example since I have a default value which contains a number, which is not allowed, everything I type is replaced with previous value because the regex keeps coming back as invalid.
How could I build this so that, if the default value is invalid, the user can still add additional VALID values without having to remove the default invalid values first?

If you want to have the invalid data and a valid one in the same input I'm not seeing how it will happened with your approach.
If you want to have an initial value (that can be either valid or invalid) and then to append something (which is valid) then why are you checking for the initial state.
The third variant is to have both
Empty field and putting a valid chars only
Initial value (valid or invalid) and appending something (valid)
And the result will be to have a valid stuff.
Please place your question / requirement in a more structured manner.
As for the code I would suggest to change your regex. I can give suggestions for modification. :)
For the code:
<input id="myInput" type="text" value="co vi1d-" />
<p id="messageField"></p>
(function() {
const pattern = new RegExp(/^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g);
const messageField = document.getElementById('messageField');
function validateInput(event) {
var newValue = event.target.value; // no sense to have a check and to overwrite with window.event , its a different context
messageField.innerText = pattern.test(newValue) ? '' : 'incorrect input'; // its better to use test() method rather than match()
}
document.getElementById('myInput').oninput = validateInput;
}());

Related

Vue3/Javascript - Unable to create an input that only excepts numbers

I have a project with a input that only excepts numbers.
Inside the template I have defined a input with the value set to the variable that is being changed and the input being set to the function that checks if it is a number:
<input
:value="ie"
#input="(evt) => changeIE(evt)"
type="number"
min="0"
/>
Then in the setup function I have declared a ref ie. This contains the actual value that is being set by the input. I also have declared the `changeIE' function. Here I first get the input text from the evt. Then I check if the last entered character is a number. If not I remove the last character from the string. The next step is to parse the string to an Integer. And lastly I set the value of the variable to the new value of the input.
const ie = ref('');
const changeIE = (evt) => {
let value = 0;
let input = evt.target.value;
let isnum = /^\d+$/.test(input[input.length - 1]);
if (!isnum) input = input.slice(0, -1);
if (input !== '') value = parseInt(input);
ie.value = value;
};
The problem is that the input keeps on excepting non numerical numbers even tough I check if they are numbers and if not I remove that character from the string.
Try to use the v-model with number as modifier and set initial value to 0 :
<input
v-model.number="ie"
type="number"
min="0"
/>
and :
const ie=ref(0)
DEMO
try
const ie = ref(null) // instead of ref('')
By default you set it to a string

How to prevent the input field from accepting more than 2 decimal places in react native?

Restrict input field from accepting more than 2 decimal places. In most of the places, This is recommended, But instead of validating later, I dont want to allow more than 2 decimal places in the input field itself.
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
</script>
</head>
<body>
<p> Enter the number</p>
<input type="text" id="resultText" oninput="validate(this)" />
You could try this.
Set up your state for the input: const [value, setValue] = useState()
Then in your TextInput callback onChangeText, set it up like this.
onChangeText={(text) => {
const validated = text.match(/^(\d*\.{0,1}\d{0,2}$)/)
if (validated) {
setValue(text)
}
}}
This validates a string first to match the following pattern:
zero or more digits
followed by 0 or 1 decimal place
followed by 0, 1, or 2 decimal places (but no more than 2)
I also start the regex with a ^ which forces the match to start at the beginning of the text.
The text argument that is passed in to onChangeText is the entire string (not just the next character). If this string doesn't conform to the regex we set up (validation) then we ignore this value and the state isn't updated.
I'm sure there are other ways to do this, but this one worked for me.
Let me also add this: in React Native's TextInput you can control the keyboard type. Mine is set to a numeric keyboard so the user never gets a chance to enter a letter. This should work either way. It's just a side note
<input pattern='d\+\.\d\d$'/>
You can specify a regex pattern on the input and tell it to only accept numbers (\d), along with a dot and only two numbers after the dot.
I have no idea if that works in react native, only in browsers.
You don't necessarily have to resort to regex.
You can simply use conditionals of substrings on top of regex.
const onChangeText = (text) => {
// Only allow "number & ." input
const cleanNumber = text.replace(/[^0-9.]/g, "")
// Only take first 2 values from split. Ignore the rest.
const strAfterDot = cleanNumber.split('.', 2)[1]
if (strAfterDot.length <= 2){
console.log("setValue now")
setValue(text)
} else {
console.log("Should not be allowed. You can trim the value yourself.)
const strBeforeDot = cleanNumber.split('.', 1)[0]
setValue(strBeforeDot + '.' + strAfterDot.substr(0, 2))
}
}
(Not tested for edge-cases, I'll leave that up to you.)

Number only validation not working in ionic app

<input type="tel" (keydown)="numberOnlyValidation($event)">
// Function not able to read input number values
// On typing into the input field nothing in showing mainly not able to read the keyboard number values
numberOnlyValidation(event: any) {
console.log(event.target.value)
//pattern
const pattern = /[0-9]/;
const inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
``
The .charCode property only exists on the keypress event Keyboard Event (developer.mozilla.org)
The specification says to use the KeyboardEvent.key property instead (developer.mozilla.org)
Apart from handling delete, your code should work if you change this line to utilize event.key
const inputChar = String.fromCharCode(event.charCode); // remove
const inputChar = event.key; // add

Validate salary input jQuery

I'm trying to validate input value must be like 1.400,00 and 12.000,00.
If input has the correct value, it should remove the disabled class from the else stays disabled.
I tried like this but did't get success :(
<input id="ex2" class="salary" type="number" placeholder="1.400,00 - 12.000,00" name="salaryRange2"/>
Next Step
$("#ex2").on("keyup", function(){
var valid = /^\d{1,6}(?:\.\d{0,2})?$/.test(this.value),
val = this.value;
if(valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
$("#checkSalary1").removeClass("disabled");
}
else{
$("#checkSalary1").addClass("disabled");
}
});
Can anyone help how can achieve this condition?
Thanks in advance
Your regex is way out, something like this gets you a little closer:
^\d{1,2}.\d{3},\d{2}$
Which looks for:
1-2 digits
a literal .
3 digits
a literal ,
2 digits
You may like to enhance this to make the decimal portion optional.
From there, you need to actually parse the string to a number to check it is within the valid numerical range (as, for example 95.000,00 would pass on a regex check, but not in the range check.
The number input value is a ... Number, so you can just use a numeric comparison, no RegExp needed. Furthermore, the keyup event will not trigger if you use a mouse to increment or decrement its value.
Here's a snippet that continuously checks the salary input value, enables or disables the button as applicable and shows a message about the input value validity. To make your live even easier, for a [type=number]-input you can also set a minimum and maximum value by the way (used in the snippets checkValue method).
See also
(() => {
const inputElement = document.querySelector("#ex2");
const report = document.querySelector("#report");
const bttn = document.querySelector("button");
const getAction = cando => cando ? "removeAttribute" : "setAttribute";
const checkVal = val => val
&& val >= +inputElement.getAttribute("min")
&& val <= +inputElement.getAttribute("max");
const messages = {
cando: "Ok to submit",
noValue: "Waiting for input (1.400,00 - 12.000,00)",
invalid: "Value should be from 1.400,00 up to 12.000,00"
};
inputElement.focus();
checkValue();
function checkValue() {
const val = inputElement.value;
const cando = checkVal(val);
report.innerHTML = !val
? messages.noValue
: cando
? messages.cando
: messages.invalid;
bttn[getAction(cando)]("disabled", true);
return setTimeout(checkValue, 200);
}
})();
<input id="ex2"
class="salary"
type="number"
min="1400"
max="12000"
step="0.01"
name="salaryRange2"/>
<button disabled>submit</button> <span id="report"></span>

Javascript Regexp Format

I'm a beginner in JavaScript. I tried every tutorial/site and couldn't find an answer. I couldn't understand some examples.
I want to put a specific format and validate if the users input is correct.
Here is my code:
var expD = document.getElementById("ccN");
var re = new RegExp("[0-9][0-9]/[0-9][0-9]");
if (re.test(expD))
bootbox.alert("Correct");
else
bootbox.alert("Wrong");
expD is DOMElement, you cannot use it as if it is string
You need to bind event on textbox/button, to check if the value entered by user is in valid format
The regular expression needs ^ and $ anchors, if you want to check if the complete string is in the valid format
In your case expD is a dom element, I think you need to get the value and test it
function testit() {
var expD = document.getElementById("ccN").value;
var re = /^\d{2}\/\d{2}$/;
if (re.test(expD)) {
alert("Correct");
} else {
alert("Wrong");
}
}
<input id="ccN" />
<button onclick="testit()">Test</button>

Categories

Resources