So I have to get an input value in attr=value format.
Something like name=John or surname=Doe. The string could contain number but no symbol other then = is allowed.
Now, I need to validate the field in Javascript. I have already got a regex, which goes something like this /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/. Its working fine. However, I feel like there might be a better regex to do this. Also, if user inputs something like name=John-, it allows it. Which should not be the case. If you guys could point me to the right direction, it would be great.
var regexField = $('#regex-test'),
RegEx = /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/,
isValid = function(element){
return RegEx.test(element.val());
};
$('#submit').click(function(e){
if(isValid(regexField)){
$('#err').hide();
return;
}
$('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>
Your expression is not far off from what you want. The reason it's allowing name=John- is because there is no anchoring to the ends of the string. It will also accept, for example, #$%name=John-!?foo. To anchor to the start use ^ and $ for the end.
You don't need to put the = in a character class (as you've only got one option); and you definitely don't want to quantify it with + as you want exactly one (not one or more).
Finally, you can simplify it a little bit by making it case-insensitive, using the i flag.
Ultimately, this gives you:
/^[a-z0-9]+=[a-z0-9]+$/i
You can make it even simpler if you allow underscores in your attributes and values: then you can change [a-z0-9] to \w...but that's your call :)
A version that allows whitespace around the =, and allows only whitespace after the name=value portion (and so disallows symbols at the end), would be:
RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i
var regexField = $('#regex-test'),
RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i,
isValid = function(element){
return RegEx.test(element.val());
};
$('#submit').click(function(e){
if(isValid(regexField)){
$('#err').hide();
return;
}
$('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>
Related
I have the following HTML5 form:
<form id="address-form" method="POST">
// ...other inputs that work fine
<input type="text" name="street_number" class="form-control" placeholder="Street No.*" tabindex="3" required pattern="\d+(-\d+)?[A-Z]?" title="Please enter only digits separated by a single optional hyphen, with a single optional letter suffix.">
<input type="text" name="street_address" class="form-control" placeholder="Address*" tabindex="4" required pattern="[A-z ]+" title="Please enter only letters and spaces.">
// ...other inputs that work fine
</form>
And the following jQuery:
let form = $('#address-form');
form.find('[required]').each((i, elem) => {
invalidElem = $(elem);
// ...more unrelated code
if (elem.name === 'password1' && elem.value !== '') {
password = elem.value;
}
if (elem.name === 'password2') {
elem.setCustomValidity(elem.value === password ? '' :
'This field must match the password field.');
}
invalidElem.removeAttr('style');
return (isValid = elem.reportValidity());
});
I am testing validation of the first input shown with the string "180-186" and it is failing. Why?
According to https://regex101.com/ this should work fine in JavaScript, which I assume is the regex engine used by browsers to validate pattern attributes...but Chrome (at least) seems to disprove that assumption, so if anyone definitively knows the actual regex engine used by browsers I'd love to know.
In case it's not obvious to anyone, this input needs to take the street number portion of an address. So "143", "22A", "180-186" and "1-7A" should all match, but having the letter anywhere but the end should not match, nor should anything with multiple hyphens, letters or any spaces.
I'd also accept any answer that suggests a reasonable compromise to my strict definition of a house or building number.
It turns out that VS Code had simply turned my hyphen into an em dash when I was typing static values into the HTML...d'oh!
Anyway thanks to everyone who commented for trying to help :-)
Could anyone help with this?
Code allowing the user to input a username and a password, both of which must be validated as follows:
The username may only contain letters, dots (.), the at sign (#). The username must NOT be longer than 25 characters.
In order to limit to 25 characters, the easiest way is to use an
<input type="text" maxlength="25" />
In order to validate that input only contains letters, dots (.) and #, proceed with a regular expression.
Example:
<input id="input" type="text" maxlength="25" />
<button id="button">Test</button>
<br/>
<div id="validation" />
$(document).ready(function(){
var $text = $('#input');
var $btn = $('#button');
var $out = $('#validation');
$btn.on('click', _do_check);
function _do_check(e){
e.preventDefault();
e.stopPropagation();
var text = $text.val();
if (/^[a-zA-Z.#]+$/.test(text) ){
$out.html('OK');
} else {
$out.html('FAILURE');
}
}
});
Hope this helps.
Using only plain Javascript:
You will need to construct a regular expression. Check this to get an idea how it works in Javascript https://www.w3schools.com/jsref/jsref_obj_regexp.asp
The following expression would be a regular expression fitting your username requirements with the only allowed characters and the length restrictions at once
/^([a-zA-Z\.\#]{1,25})$/
You can play and learn how to build a regular expression with pages like https://regexr.com/
And as recommended you should start with some of your work in order to help actually with a problem and then the community can guide you to solve your real issue.
I have 5 text boxes I will get prices how can I validate there is only numbers on those text boxes if there is a letter I want to give a alert when submit.
How can I do that please help me Im new to these stuff
<input type="text" id="sellingPrice"><br>
<input type="text" id="basicPrice"><br>
<input type="text" id="latestBuyingPrice"><br>
<input type="text" id="ReorderQuantity"><br>
<input type="text" id="reorderLevel"><br>
<button id="save_P" type="button" class="save-button-text save-button displayShow" onclick="submitDetails()">
how can I use number validation in submitDetails() method
This is a pretty common issue, but there are a couple ways to approach it:
Verify using Regular Expressions
Attempt to parse the number and check if isNaN(parsedResult) returns true
By far, I believe the most common approach is var num = parseFloat(StringNumberFromTextbox), isValidNumber = (!isNaN(num) && isFinite(num));
If you went the RegEx route, you could use: var rNumPattern=/^\d+(\.\d+)?$/, isValidNumber = rNumPattern.test(StringNumberFromTextbox);
You might also consider consider checking negative/positive signs and thousands separators using replacements of commas or periods (as appropriate for the locale/clientele).
Of course, if you are then submitting those on a form to some backend processor, you would be wise to check those numbers again on the server-side rather than blindly trusting that the client has provided valid numbers just because your JavaScript should done the checking. Lest you end up with a SQL vulnerability or the like.
You can add type="number" attribute to input tag.
In submitDetails() use following code.
var sellingPrice=document.getElementById("sellingPrice").value;
//repeat above code for all field.
if(Number.isInteger(sellingPrice) == false){
alert('wrong value entered');
}
//repeat above if code for all value.
This will do what you want.
You can check it using isNaN(value) inbuilt function of JavaScript.
Your function could be like this:
function submitDetails() {
var val = document.getElementById("sellingPrice").value;
if (isNaN(val)) {
// show alert here
}
}
Help make the correct regular expression for the search 3 words into the field. So far I have done so, but I think it's crazy.
var inp = document.getElementsByTagName('input')[0],
button = document.getElementsByTagName('button')[0];
button.onclick = function() {
console.log(inp.value.match(/^([а-яa-z0-9]+ ){2}[а-яa-z0-9]+/i));
};
<input type="text" />
<button>Check</button>
I guess it's easier to split the text and then verify that the element count is as you expect it. You may want to trim the text before to avoid leading and trailing empty strings in the result array.
console.log(inp.value.trim().split(/\s+/))
I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.
I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.
<script type="text/javascript">
function scrub(text) {
var commands = new Array{"someCommand","anotherCommand",...};
for (var i = 0; i <= commands.length; i++) {
if (text.value.toLowerCase().equals(commands[i])) {
//command is valid; do something here
} else {
alert("Invalid command");
}
}
text.value = ""; //clears the text box
}
</script>
For your textarea do this:
<textarea onblur="scrub(this);" ...></textarea>
Is there a set of keywords? And can be they be combined only in a certain fashion?
Looks like couple of regex patterns will be able to do the trick.
e.g: to match "9030 OUT FU [1234 TEST]" regex would be: /\d{4} OUT FU \[\d{4}\]/.
OUT FU and can be substituted with \w{3} and \w{2} respectively (unless you do not want any word to be allowed).
Use regular expressions.
html:
<input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />
javascript:
function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}
http://gskinner.com/RegExr/ is very helpful with regular expressions.
When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.