Javascript Regexp Format - javascript

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>

Related

Prevent invalid formats based on given regex

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;
}());

Check if value matches mask

I have a input that has a mask of date like __/__/____. I stored it in a variable. Is there a way to detect if it matches the mask properly?
The event is binded on blur, so sometimes it is returning values like 22/12/___.
Is there a way to detect if it definitely fits the scheme with integers and slash only or doesn't?
$('#btn').click(function() {
value = $('#my-input').val() // should be in this format 99/99/9999 and not 12/12/12__
// here I need to check if it is in right format.
if (checkFormat(value)) {
}
}
You can use regex to validate this.
var regex_check = /^\d{2}\/\d{2}\/\d{4}$/ ;
//Edit - Vanilla JavaScript
function foo(date) {
var regex_pattern = /^\d{2}\/\d{2}\/\d{4}$/ ;
var check = new RegExp(regex_pattern);
var res = check.test(date);
// return true or false
return res;
}
Use match() with the following regex : ^\d{2}\/\d{2}\/\d{4}$
your code will be like :
$('#btn').click(function() {
value = $('#my-input').val();
if (value.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
alert("match");
}
else {
alert('the value does not match the regular expression');
}
}

Find and remove text from input value string

Our form has a hidden input that contains all the required values we send to the server for server-side validation. This is formed of a comma-separated string:
i.e. <input type="hidden" value="name,address,telephone,email">
We now have new inputs (i.e. website) that appear on a radio button check and I can successfully add these to the value="" string:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
But when a different radio is checked, I can't get it to remove ,website from the string.
I believe I need to grab the string, split it by comma, find and remove website and then re-join the string, but I'm not sure how to implement this (or if this is even the best way):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}
You can use string.indexOf(searchValue); and string.replace(oldValue, newValue); to search and remove non-selected elements or better pass Regular expression in the first parameter of string.replace(regex, newValue):
Non-regex Example:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
nowReq = nowReq + ',website';
}
else {
if(string.indexOf(',website') > -1) // If website is the last element
nowReq = nowReq.replace(',website', '');
else if(string.indexOf('website,') > -1) // If website is not the last element
nowReq = nowReq.replace('website,', '');
}
$('input[name="required"]').val(nowReq);
You simply need to remove the last element in your array and join it with the ',' character :
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));
Try:
var splitReq = nowReq.split(',website').join("");
the following would work in most cases:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");
I'd suggest that you avoid parsing the value string, and simply recalculate the value on the change of the relevant input elements; the following is a demonstrative example because of the lack of information presented in the question (a more specific example could be provided if we can see your HTML, and current jQuery, rather than a description of it):
$('input[type="checkbox"]').on('change', function(){
var requiredString = $('input[type="checkbox"]').map(function(){
if (this.checked) {
return this.value;
}
}).get().join(',');
$('input[name="required"]').val(requiredString);
}).change();
JS Fiddle demo.
References:
change()
filter()
get()
map()
on()

Javascript - Detecting the first character and alerting the user

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

Find the first character of input in a textbox

I am stuck in implementing the following:
User starts typing in a textbox.
The javascript on page captures the first character typed, validates that it is an english alphabet (a-z,A-Z) and converts it to lowercase (if necessary).
Make an XMLHttp request based on the input (i.e. if first input character is a, get a.xml, if b get b.xml and so on).
I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.
Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.
Something like this should work:
HTML:
<input type="text" id="myField" />
And in JS:
window.onload = function() {
document.getElementById('myField').onkeyup = function() {
// Validate that the first letter is A-Za-z and capture it
var letter = this.value.match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
// Do the request
}
}
}
My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:
$(function() {
$('#myField').keyup(function() {
var letter = $(this).val().match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
$(this).val(letter + $(this).val().substring(1);
// Do the request
}
});
});
What part of the problem do you not know how to do? Here's an approach that you can follow. Very likely to need adjustments, but a good starting point
if our text field's id is 'txt'
document.getElementByID('txt').onkeypress = function(e) {
var textInField = this.value;
if (textInField.length == 1) {
var firstChar = textInField.charAt(0);
if (/[a-zA-Z]/.test(firstChar)) {
sendXHR(textInField.value.toLowerCase())
}
} else {
// What do you do if there is one or more chars???
}
}
Note that the other answers here mention onchange, that doesn't fire until the focus leaves the field, which I don't think is what you want

Categories

Resources